import javax.swing.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; // CutPaste.java - program demonstrating String Cut and Paste - ref: Java Examples in a Nutshell by David Flanagan public class CutPaste extends Frame implements ActionListener { // create frame, be able to close it, pack it, pop it private static final long serialVersionUID = 1278345L; public static void main(String[] args) { Frame ourf = new CutPaste(); ourf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); ourf.pack(); ourf.setVisible(true); //show(); } TextField ourfield; // Text field with String data public CutPaste() { // Constructor this.setFont(new Font("Verdana", Font.PLAIN, 14)); // Cut button ... Button ourcut = new Button("Cut"); ourcut.addActionListener(this); ourcut.setActionCommand("cut"); this.add(ourcut, "West"); // Past button ... Button ourpaste = new Button("Paste"); ourpaste.addActionListener(this); ourpaste.setActionCommand("paste"); this.add(ourpaste, "East"); // Text field ... ourfield = new TextField(); this.add(ourfield, "North"); } public void actionPerformed(ActionEvent e) { // click logic String ourcmd = e.getActionCommand(); if (ourcmd.equals("paste")) { dopaste(); } else if (ourcmd.equals("cut")) { docut(); } } public void docut() { // cut method String ours = ourfield.getText(); // text field's string StringSelection ourss = new StringSelection(ours); // use StringSelection object this.getToolkit().getSystemClipboard().setContents(ourss, ourss); // contents and owner of clipboard are StringSelection object } public void dopaste() { // paste method Clipboard ourc = this.getToolkit().getSystemClipboard(); // set up Clipboard object Transferable ourt = ourc.getContents(this); // Clipboard contents to Transferable object try { String ours = (String)ourt.getTransferData(DataFlavor.stringFlavor); ourfield.setText(ours); } catch (Exception oure) { this.getToolkit().beep(); // oops return; } } }