Java Reference
In-Depth Information
Example 13−1: SimpleCutAndPaste.java (continued)
this.add(field, "North");
}
/**
* This method takes the current contents of the text field, creates a
* StringSelection object to represent that string, and puts the
* StringSelection onto the clipboard
**/
public void copy() {
// Get the currently displayed value
String s = field.getText();
// Create a StringSelection object to represent the text.
// StringSelection is a pre-defined class that implements
// Transferable and ClipboardOwner for us.
StringSelection ss = new StringSelection(s);
// Now set the StringSelection object as the contents of the clipboard
// Also specify that we're the clipboard owner
this.getToolkit().getSystemClipboard().setContents(ss, this);
// Highlight the text to indicate it is on the clipboard.
field.selectAll();
}
/**
* Get the contents of the clipboard, and, if we understand the type,
* display the contents. This method understands strings and file lists.
**/
public void paste() {
// Get the clipboard
Clipboard c = this.getToolkit().getSystemClipboard();
// Get the contents of the clipboard, as a Transferable object
Transferable t = c.getContents(this);
// Find out what kind of data is on the clipboard
try {
if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// If it is a string, then get and display the string
String s = (String) t.getTransferData(DataFlavor.stringFlavor);
field.setText(s);
}
else if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
// If it is a list of File objects, get the list and display
// the name of the first file on the list
java.util.List files = (java.util.List)
t.getTransferData(DataFlavor.javaFileListFlavor);
java.io.File file = (java.io.File)files.get(0);
field.setText(file.getName());
}
}
// If anything goes wrong with the transfer, just beep and do nothing.
catch (Exception e) { this.getToolkit().beep(); }
}
/**
Search WWH ::




Custom Search