clipboard acts as a temporary staging area where application users store cut or copied information, including text, graphics, objects, and other data types. It is a heavily exploited data sharing facility. Therefore, when developing new applications, it makes sense to expend extra effort to support the clipboard. Neglecting clipboard functionality can result in an application that gets complaints, requires new development, orworst of allnever gets used.
But how does one go about writing to and reading from the clipboard using Java? Sun Microsystems provides the java.awt.datatransfer package as part of the Java framework, which allows you to support the clipboard. In this article, you'll learn how to copy/cut and paste both text and images using java.awt.datatransfer.
The Data Transfer Framework
The framework that makes cutting/copying/pasting possible in Java was introduced in Java 1.1 with the java.awt.datatransfer package. Core to the data transfer framework are the java.awt.datatransfer.DataFlavor class and the java.awt.datatransfer.Transferable interface.
The DataFlavor Class
The java.awt.datatransfer.DataFlavor class describes the data types and data formats you'll be transferring on the clipboard. The clipboard can be used to stage a variety of types of data, like text, graphics, and sound files. Because of this, you need a way to describe what type of data is being written to/read from the clipboard. Think of the DataFlavor object as the holder of metadata which defines the clipboard item. Describe the data type defined by DataFlavor using a MIME type. This is exemplified in the syntax below, which creates a new DataFlavor object named jpegFlavor. The first argument of the constructor is the MIME type ("image/jpeg") and the second argument is a human-readable name for the data type ("JPEG image").
DataFlavor jpegFlavor = new DataFlavor("image/jpeg","JPEG image");
In cases where you're planning to pass clipboard data between different JVMs, you can also define a DataFlavor using a class definition. When you put Java objects on the clipboard, object serialization is used behind the scenes to transfer a given object from one JVM to another. The code below shows how to create a Flavor object for the java.awt.Polygon class
. Again, the second argument represents the human readable form you want associated to the Flavor. The first constructor argument represents the class name of the object for which you’re defining the Flavor object:
DataFlavor polygonFlavor = new DataFlavor(java.awt.Polygon.class,
"Java Polygon Object");