The Transferable Interface
While the DataTransfer class defined the type of the data you're placing on the clipboard, you still need an object type to transfer the data payload. To do this, put the data in an object that implements the java.awt.datatransfer.Transferable
When you transfer a clipboard item from one application to another, the application to which you are pasting might not understand the source data in its proprietary format. For example, when you copy Microsoft Word text, it will contain certain information with it about text formatting. When you paste this clipboard item to Notepad, the item is copied, stripping all the formatting from the original clipboard item.
To replicate this in the Java world, you can have the object that you place on the clipboard support multiple MIME types. In the example above, you could support the MIME type of "application/msword" (representing Microsoft Word) as well as the MIME type of "text/plain" (representing plain text).
The Transferable interface requires upi to implement three methods:
- DataFlavor getDataTransferDataFlavors(): This method returns an array of DataFlavor objects. It tells you what Flavor types are supported by a given Transferable implementation.
- public boolean isDataFlavorSupported(DataFlavor flavor): This method takes in a given DataFlavor and tells you if it is supported by the given Transferable implementation
- public Object getTransferData(DataFlavor flavor): this method takes in a given DataFlavor and returns an Object that contains the payload of the clipboard item. The object is returned either as a serialized Java Object or a java.io.InputStream object, depending on the type of DataFlavor that was passed in. This method can throw a java.awt.datatransfer.UnspportedFlavorException if the requested DataFlavor does not fall in the list of DataFlavors for which you have claimed support.
Local & System Clipboards
Java has two different types of clipboards: local and system. Local clipboards are available only within the Java Virtual Machine (JVM). You can also have multiple local clipboards. Unfortunately, with local clipboards, you can't interact with the clipboard of your operating system. The System clipboard provides you this facility.
Use the following syntax to get a reference to the system clipboard (represented by a Clipboard object):
Clipboard systemClipboard =
To create a local clipboard, use the Clipboard constructor, which takes in a name for your clipboard:
Clipboard localClipboard = new Clipboard("My local clipboard");