Java Reference
In-Depth Information
program performs a copy operation rather than a cut operation. To do a cut, sim-
ply delete the text from the source after copying it to the clipboard. The interest-
ing code is in the copy() and paste() methods towards the end of the example.
Also note that the example implements ClipboardOwner , so it is notified when its
data is no longer on the clipboard. The best way to test this program is by starting
two independent copies of it and transferring data between them. You can also try
transferring data between an instance of this program and a native application on
your platform.
Example 13−1: SimpleCutAndPaste.java
package com.davidflanagan.examples.datatransfer;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
/**
* This program demonstrates how to add simple copy-and-paste capabilities
* to an application.
**/
public class SimpleCutAndPaste extends Frame implements ClipboardOwner
{
/** The main method creates a frame and pops it up. */
public static void main(String[] args) {
Frame f = new SimpleCutAndPaste();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
f.pack();
f.setVisible(true);
}
/** The text field that holds the text that is cut or pasted */
TextField field;
/**
* The constructor builds a very simple test GUI, and registers this object
* as the ActionListener for the buttons
**/
public SimpleCutAndPaste() {
super("SimpleCutAndPaste"); // Window title
this.setFont(new Font("SansSerif", Font.PLAIN, 18)); // Use a big font
// Set up the Cut button
Button copy = new Button("Copy");
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { copy(); }
});
this.add(copy, "West");
// Set up the Paste button
Button paste = new Button("Paste");
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { paste(); }
});
this.add(paste, "East");
// Set up the text field that they both operate on
field = new TextField();
Search WWH ::




Custom Search