最近 小研究了一哈 java swing 这东西,感觉java在这方面还是不错
此小节 JTextArea 实现了copy和past 用到了几个方法
首先为了以后方便做了一个启动类(很简单的一个东西)
public class DoMain { public static void main(String[] a){ SwingUtilities.invokeLater(new Runnable() { public void run() { JTextAreaTest tb = new JTextAreaTest();//以后直接把此行替换就行了 tb.setLocationRelativeTo(null); tb.setVisible(true); } }); } }
JTextAreaTest 类:
@SuppressWarnings("serial") public class JTextAreaTest extends javax.swing.JFrame { private JMenuBar jMenuBar1; private JMenuItem mucopy; private JMenuItem mupast; private JScrollPane jsp; private JTextArea jta; private JMenu jMenu1; public JTextAreaTest() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { jsp = new JScrollPane(); getContentPane().add(jsp, BorderLayout.CENTER); { jta = new JTextArea(); jsp.setViewportView(jta); } } { jMenuBar1 = new JMenuBar(); setJMenuBar(jMenuBar1); { jMenu1 = new JMenu(); jMenuBar1.add(jMenu1); jMenu1.setText("\u7f16\u8f91"); { mucopy = new JMenuItem(); jMenu1.add(mucopy); mucopy.setText("\u590d\u5236"); } { mupast = new JMenuItem(); jMenu1.add(mupast); mupast.setText("\u7c98\u8d34"); mupast.setEnabled(false); } mucopy.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ActionListenerTest ap = new ActionListenerTest(); mupast.setEnabled(ap.copy(e, jta.getText())); } }); mupast.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ActionListenerTest ap = new ActionListenerTest(); jta.replaceRange(ap.past(e),jta.getSelectionStart(),jta.getSelectionEnd()); // jta.setText(jta.getText()+ap.past(e)); } }); } } pack(); this.setSize(546, 359); } catch (Exception e) { e.printStackTrace(); } } }
把actionlistener 的方法都写到例外一个类里面了 大体上让主体上代码好看些
public class ActionListenerTest { public String past(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if(clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)){ try { String content = (String)clipboard.getData(DataFlavor.stringFlavor); return content; } catch (UnsupportedFlavorException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } return "copy"; } public boolean copy(ActionEvent e,String content) { StringSelection contents = new StringSelection(content); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(contents, null); if(clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)){ return true; } return false; } }
效果图
(也可见附件)
刚开始做的一个东西 , 功能很少 、、、一步步让它更强大