Java swing 常用代码片段:
(1)复制全部
JButton copyAll=new JButton("复制全部"); copyAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String content=area2.getText(); if(ValueWidget.isNullOrEmpty(content)){ return; } WindowUtil.setSysClipboardText(content); } }); public static void setSysClipboardText(String writeMe) { Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(writeMe); clip.setContents(tText, null); }
获取一个"复制"按钮
/*** * Get a copy button. * * @param tf * @return */ public static JButton getCopyBtn(final JTextComponent ta) { JButton copyBtn = new JButton(MenuUtil2.ACTION_STR_COPY); copyBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(ValueWidget.isNullOrEmpty(ta)){ ToastMessage toastMessage = new ToastMessage("文本框为null,请确认文本框是否已经创建",3000,Color.red); toastMessage.setVisible(true); }else{ String input = ta.getText(); if (!ValueWidget.isNullOrEmpty(input)) { WindowUtil.setSysClipboardText(input); } } } }); return copyBtn; }
(2)黏贴
btnPasteAfterDel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String content = WindowUtil.getSysClipboardText(); if (ValueWidget.isNullOrEmpty(content)) { return; } getTextArea().setText(content); } });
获取一个黏贴按钮:
/*** * Get a paste button. * * @param ta * @return */ public static JButton getPasteBtn(final JTextComponent ta) { JButton copyBtn = new JButton(MenuUtil2.ACTION_STR_PASTE); copyBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String input = WindowUtil.getSysClipboardText(); if (!ValueWidget.isNullOrEmpty(input)) { ta.setText(input); } } }); return copyBtn; }
(3)给JTextArea 增加快捷键
final JTextArea ta=getTextArea(); KeyListener[] keyListeners=ta.getKeyListeners(); ta.addKeyListener(new KeyAdapter() { private long lastTimeMillSencond; private long lastTimeMillSencondCtrl; private long lastTimeMillSencondEsc; @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_A/*全选*/ ||e.getKeyCode() == KeyEvent.VK_C/* 复制 */ ||e.getKeyCode() == KeyEvent.VK_F/*格式化*/ ||e.getKeyCode() == KeyEvent.VK_Z/*剪切*/ ||e.getKeyCode() == KeyEvent.VK_V){ // System.out.println(e.getKeyCode()); lastTimeMillSencondCtrl=0; } if(e.isShiftDown()){ if(lastTimeMillSencond==0){ lastTimeMillSencond=System.currentTimeMillis(); }else{ long currentTime=System.currentTimeMillis(); long delta=currentTime-lastTimeMillSencond; if(MenuUtil2.isDoubleClick(delta)){ // System.out.println("双击Shift"); lastTimeMillSencond=0; String selectContent = ta.getSelectedText(); if(ValueWidget.isNullOrEmpty(selectContent)){ return; } selectContent=SystemHWUtil.deleteQuotes(selectContent); ta.replaceSelection(selectContent); }else{ lastTimeMillSencond=System.currentTimeMillis(); } } }else if(e.isControlDown()&&(e.getKeyCode() != KeyEvent.VK_V/*86 */&&e.getKeyCode() != KeyEvent.VK_Z/*90*/ &&e.getKeyCode() != KeyEvent.VK_C/*67*/&&e.getKeyCode() != KeyEvent.VK_A/*65*/)){//双击Ctrl // System.out.println(e.getKeyCode()); // System.out.println("lastTimeMillSencondCtrl:"+lastTimeMillSencondCtrl); if(lastTimeMillSencondCtrl==0){ lastTimeMillSencondCtrl=System.currentTimeMillis(); }else{ long currentTime=System.currentTimeMillis(); long delta=currentTime-lastTimeMillSencondCtrl; // System.out.println(lastTimeMillSencondCtrl+" "+currentTime+" "+delta); if(MenuUtil2.isDoubleClick(delta)){ System.out.println("双击Ctrl"); lastTimeMillSencondCtrl=0; String selectContent = ta.getSelectedText(); if(ValueWidget.isNullOrEmpty(selectContent)){ return; } quotesEscape(ta,false); }else{ lastTimeMillSencondCtrl=System.currentTimeMillis(); } } }else if(e.getKeyCode() == KeyEvent.VK_ESCAPE){ if(lastTimeMillSencondEsc==0){ lastTimeMillSencondEsc=System.currentTimeMillis(); }else{ long currentTime=System.currentTimeMillis(); if(MenuUtil2.isDoubleClick(currentTime-lastTimeMillSencondEsc)){ // System.out.println("双击Esc"); lastTimeMillSencondEsc=0; String content = ta.getText(); if(ValueWidget.isNullOrEmpty(content)){ return; } boolean isEditable=ta.isEditable(); ta.setEditable(!isEditable); }else{ lastTimeMillSencondEsc=System.currentTimeMillis(); } } } } }); ta.requestFocus();
MenuUtil2.isDoubleClick 实现如下:
/*** * 通过时间间隔来判断是否是双击(不是鼠标,是键盘) * @param delta * @return */ public static boolean isDoubleClick(long delta){ return (delta<300&&delta>100); }
(4)使JTextArea 自动换行
resultTextPane = new AssistPopupTextArea(); resultTextPane.setLineWrap(true); resultTextPane.setWrapStyleWord(true);
(5)设置表格数据
private void setTableData2(Object[][] datas) { DefaultTableModel model = new DefaultTableModel(datas, columnNames); parameterTable_1.setModel(model); this.parameterTable_1.setRowHeight(30); rendTable(); }
(6)获取表格的数据
/*** * 获取表格中的请求要素 * * @return */ protected Object[][] getParameter4Table(){ TableModel model= parameterTable_1.getModel(); int rowCount = model.getRowCount();//参数的个数 int columnCount=model.getColumnCount(); Object[][] data2 = new Object[rowCount][]; for (int rowIndex = 0; rowIndex< rowCount; rowIndex++) { if (!ValueWidget.isNullOrEmpty(model.getValueAt(rowIndex, 0))) { Object[] objs = new Object[columnCount]; for (int j = 0; j < columnCount; j++) { Object val = model.getValueAt(rowIndex, j); if (!ValueWidget.isNullOrEmpty(val)) { objs[j] = val; } } data2[rowIndex] = objs; } } System.out.println(data2.length); return data2; }
(7)获取组件对话框中的数据
String newName = JOptionPane.showInputDialog(ta.getParent()/*应该是JFrame*/, "请输入图片高度:", ta.getHeight()); if (newName != null) { if (newName.equals("")) { ToastMessage toastMessage = new ToastMessage("file name can not be empty.",3000,Color.red); toastMessage.setVisible(true); return; } specifiedHeight=Integer.parseInt(newName); }else{/* indicate [cancel] button has been clicked */ ToastMessage toastMessage = new ToastMessage("已取消",2000,Color.red); toastMessage.setVisible(true); return; }
(8)一个简单的模态窗口(对话框)
package com.yunma.dialog; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.EmptyBorder; import com.common.util.SystemHWUtil; import com.string.widget.util.ValueWidget; import com.swing.component.AssistPopupTextArea; import com.swing.component.AssistPopupTextField; import com.swing.component.ComponentUtil; import com.swing.dialog.GenericDialog; public class GenerateMD5Dialog extends GenericDialog { private static final long serialVersionUID = -4151740071609032069L; private JPanel contentPane; private AssistPopupTextField sourceTxt; private JComboBox<String> encodingComboBox; private AssistPopupTextArea resultTextArea; /** * Launch the application. *//* public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { GenerateMD5Dialog frame = new GenerateMD5Dialog(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }*/ /** * Create the frame. */ public GenerateMD5Dialog(boolean modal) { setTitle("生成MD5值"); setModal(modal); setLoc(450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0}; gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0}; gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE}; gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE}; contentPane.setLayout(gbl_contentPane); JLabel label = new JLabel("原文本"); GridBagConstraints gbc_label = new GridBagConstraints(); gbc_label.insets = new Insets(0, 0, 5, 5); gbc_label.gridx = 0; gbc_label.gridy = 0; contentPane.add(label, gbc_label); sourceTxt = new AssistPopupTextField(); GridBagConstraints gbc_sourceTxt = new GridBagConstraints(); gbc_sourceTxt.insets = new Insets(0, 0, 5, 0); gbc_sourceTxt.fill = GridBagConstraints.HORIZONTAL; gbc_sourceTxt.gridx = 2; gbc_sourceTxt.gridy = 0; contentPane.add(sourceTxt, gbc_sourceTxt); sourceTxt.setColumns(10); JLabel label_1 = new JLabel("文件编码"); GridBagConstraints gbc_label_1 = new GridBagConstraints(); gbc_label_1.insets = new Insets(0, 0, 5, 5); gbc_label_1.gridx = 0; gbc_label_1.gridy = 1; contentPane.add(label_1, gbc_label_1); encodingComboBox = new JComboBox<String>(); GridBagConstraints gbc_encodingComboBox = new GridBagConstraints(); gbc_encodingComboBox.insets = new Insets(0, 0, 5, 0); gbc_encodingComboBox.fill = GridBagConstraints.HORIZONTAL; gbc_encodingComboBox.gridx = 2; gbc_encodingComboBox.gridy = 1; contentPane.add(encodingComboBox, gbc_encodingComboBox); //文件的编码,window里面一般是GBK,linux中一般是UTF-8 encodingComboBox.addItem(SystemHWUtil.EMPTY); encodingComboBox.addItem(SystemHWUtil.CHARSET_UTF); encodingComboBox.addItem(SystemHWUtil.CHARSET_GBK); encodingComboBox.addItem(SystemHWUtil.CHARSET_GB2312); encodingComboBox.addItem(SystemHWUtil.CHARSET_ISO88591); //设置默认选中的项 encodingComboBox.setSelectedIndex(0); JPanel panel = new JPanel(); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.insets = new Insets(0, 0, 5, 0); gbc_panel.gridwidth = 3; gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.gridx = 0; gbc_panel.gridy = 2; contentPane.add(panel, gbc_panel); JButton generateMDbutton = new JButton("生成"); generateMDbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inputText=sourceTxt.getText(); String charset=getSelectedItem4ComboBox(encodingComboBox); if(ValueWidget.isNullOrEmpty(charset)){ charset=SystemHWUtil.CURR_ENCODING; } try { String md5 = SystemHWUtil.getMD5(inputText,charset); resultTextArea.setText(md5); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } }); panel.add(generateMDbutton); resultTextArea = new AssistPopupTextArea(); JButton btnCopy = ComponentUtil.getCopyBtn(resultTextArea); panel.add(btnCopy); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.gridwidth = 3; gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 3; contentPane.add(scrollPane, gbc_scrollPane); //结果文本域 resultTextArea.setLineWrap(true); resultTextArea.setWrapStyleWord(true); resultTextArea.setEditable(false); scrollPane.setViewportView(resultTextArea); } }
调用:
if (command.equals(MenuUtil2.ACTION_CREATE_MD5)) { GenerateMD5Dialog generateMD5Dialog=new GenerateMD5Dialog(true/*是否是模态*/); generateMD5Dialog.setVisible(true); }
(9)弹出选择文件对话框
private void chooseDestFile(JTextArea ta,String picFormat){ JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); File selectedFile=new File("C:\\Users\\Administrator\\Pictures\\"+TimeHWUtil.formatDate(new Date(), "yyyyMM")); //home目录应该动态获取 if(!ValueWidget.isNullOrEmpty(selectedFile)){ chooser.setSelectedFile(selectedFile); } chooser.setName("二维码."+picFormat); FileNameExtensionFilter filter = new FileNameExtensionFilter( "picture Files", picFormat, "二维码"); chooser.setFileFilter(filter); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setControlButtonsAreShown(true); chooser.setDialogTitle("保存二维码"); // chooser.setVisible(true); int result = chooser.showSaveDialog(ta); System.out.println("New file:" + result); if (result == JOptionPane.OK_OPTION) { selectedFile = chooser.getSelectedFile(); if(! SystemHWUtil.isHasSuffix(selectedFile)){ selectedFile=new File(selectedFile.getAbsolutePath()+ SystemHWUtil.ENGLISH_PERIOD+picFormat); } ImageHWUtil.genericImage(ta, selectedFile, picFormat); System.out.println("select file:" + selectedFile); } }
(10)在表格上增加菜单
private MouseInputListener getMouseInputListener(final JTable jTable) { return new MouseInputListener() { public void mouseClicked(MouseEvent e) { processEvent(e); } /*** * //in order to trigger Left-click the event */ public void mousePressed(MouseEvent e) { processEvent(e);// is necessary!!! } public void mouseReleased(MouseEvent e) { // processEvent(e); if (e.getButton() == MouseEvent.BUTTON3) {// right click JPopupMenu popupmenu = new JPopupMenu(); JMenuItem runM = new JMenuItem(ACTION_COMMAND_RUN); JMenuItem copyParameterM = new JMenuItem(ACTION_COMMAND_COPY_REQUEST_PARAMETER); JMenuItem copyResponseM = new JMenuItem(ACTION_COMMAND_COPY_RESPONSE); JMenuItem cleanResultM = new JMenuItem("清空结果"); // JMenuItem editM=new JMenuItem("edit"); MyMenuActionListener yMenuActionListener = new MyMenuActionListener(); runM.addActionListener(yMenuActionListener); copyParameterM.addActionListener(yMenuActionListener); copyResponseM.addActionListener(yMenuActionListener); cleanResultM.addActionListener(yMenuActionListener); popupmenu.add(runM); popupmenu.add(copyParameterM); popupmenu.add(copyResponseM); popupmenu.add(cleanResultM); popupmenu.show(e.getComponent(), e.getX(), e.getY()); } } public void mouseEntered(MouseEvent e) { processEvent(e); } public void mouseExited(MouseEvent e) { processEvent(e); } public void mouseDragged(MouseEvent e) { processEvent(e); } public void mouseMoved(MouseEvent e) { processEvent(e); } private void processEvent(MouseEvent e) { // Right-click on if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0) { // System.out.println(e.getModifiers()); // System.out.println("Right-click on"); int modifiers = e.getModifiers(); modifiers -= MouseEvent.BUTTON3_MASK; modifiers |= MouseEvent.BUTTON1_MASK; MouseEvent ne = new MouseEvent(e.getComponent(), e.getID(), e.getWhen(), modifiers, e.getX(), e.getY(), e.getClickCount(), false); jTable.dispatchEvent(ne);// in order to trigger Left-click // the event } } }; }
调用:
private void rendTable(){ parameterTable_1.getColumnModel().getColumn(2) .setCellEditor(new MyButtonEditor()); parameterTable_1.getColumnModel().getColumn(2) .setCellRenderer(new MyButtonRender()); final MouseInputListener mouseInputListener = getMouseInputListener(parameterTable_1);// parameterTable_1.addMouseListener(mouseInputListener); }
参考:
http://hw1287789687.iteye.com/blog/2230780
http://hw1287789687.iteye.com/blog/2227989
http://hw1287789687.iteye.com/blog/2173977
http://hw1287789687.iteye.com/blog/2003105