import javax.swing.*; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; public class SimpleCliboard { private Frame f = new Frame("test"); private Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); private TextArea jtaCopyTo = new TextArea(5,20); private TextArea jtaPaste = new TextArea(5,20); private Button btCopy = new Button("copy"); private Button btPaste = new Button("paste"); public void init(){ var p = new Panel(); p.add(btCopy); p.add(btPaste); btCopy.addActionListener(e -> { var contents = new StringSelection(jtaCopyTo.getText()); clipboard.setContents(contents,null); }); btPaste.addActionListener(e -> { if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)){ try { var content = (String) clipboard.getData(DataFlavor.stringFlavor); jtaPaste.append(content); } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }); var box = new Box(BoxLayout.X_AXIS); box.add(jtaCopyTo); box.add(jtaPaste); f.add(p,BorderLayout.SOUTH); f.add(box,BorderLayout.CENTER); f.pack(); f.setVisible(true); } public static void main(String[] args) { new SimpleCliboard().init(); } }
output:
原文地址:https://www.cnblogs.com/lianghong881018/p/11286556.html
时间: 2025-01-07 10:10:53