import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import javax.swing.*; public class ClipboardTest extends JFrame implements ClipboardOwner { private Clipboard clipboard; private JTextField copyFrom; private JTextArea copyTo; private JButton copy, paste; public ClipboardTest() { // Obtain a reference to the system clipboard clipboard = getToolkit().getSystemClipboard(); //Create the GUI. copyFrom = new JTextField(20); copyTo = new JTextArea(3, 20); copy = new JButton("Copy To System Clipboard"); paste = new JButton("Paste From System Clipboard"); Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(copyFrom); c.add(copy); c.add(paste); c.add(copyTo); copy.addActionListener (new CopyListener()); paste.addActionListener(new PasteListener()); //Show the frame. setSize(300, 200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); } class CopyListener implements ActionListener { public void actionPerformed(ActionEvent event) { //This is were the string is copied to the system //clipboard. //Create a transferable object that contains the //string we are copying. StringSelection contents = new StringSelection(copyFrom.getText()); // Place the transferable onto the clipboard. clipboard.setContents(contents, ClipboardTest.this); } } class PasteListener implements ActionListener { public void actionPerformed(ActionEvent event) { //This is were a string is read from the //system clipboard. //Get the content of the clipboard. Transferable contents = clipboard.getContents(this); // Determine if data is available in string flavor if(contents != null && contents.isDataFlavorSupported( DataFlavor.stringFlavor)) { try { String string; // Have contents cough up the string // that was placed on the clipboard. string = (String) contents.getTransferData( DataFlavor.stringFlavor); copyTo.append(string); } catch(Exception e) { e.printStackTrace(); } } } } public void lostOwnership(Clipboard clip, Transferable transferable) { //We must keep the object we placed on the system clipboard //until this method is called. System.out.println("Lost ownership"); } public static void main(String[] args) { new ClipboardTest(); } }