|
Drag and Drop: New Data Transfer Capabilities in the JavaTM 2 Platform, Standard Edition (J2SETM), version 1.4(5) Transferring string objects is a common task so you'll find a StringSelection class in the Java.awt.datatransfer package to help you. As it only works with strings, the class doesn't support the local/serialized types just mentioned. Now that you have some background information, let's move on to some real code. BuffersThe clipboard acts as an indirect buffer. When you make something available to the clipboard, you don't actually copy the data there. Instead, you copy a reference and that reference is Accessed when you want to take something off the buffer. Because you may need to keep track of that external reference, the clipboard will actually notify you when something else replaces an item on the clipboard. That notification is handled by the ClipboardOwner interface: public interface ClipboardOwner {public void lostOwnership(Clipboard clip,Transferable t);}This means that there is no built-in support for having multiple items on the clipboard. When something new is added to the clipboard, the old reference is thrown away. To demonstrate the use of the system clipboard, take a look at the StringSelection class. It implements both the Transferable and ClipboardOwner interfaces. You use it to transfer strings to the clipboard. Adding a string to the clipboard involves creating a StringSelection item and setting the clipboard contents, through its setContents method. Here's what the code for that task looks like. // Get StringString selection = ...;// Convert to StringSelectionStringSelection data = new StringSelection(selection);// Get system clipboardClipboard clipboard =Toolkit.getDefaultToolkit().getSystemClipboard();// Set contentsclipboard.setContents(data, data);
|