ad info

CNN.com
 MAIN PAGE
 WORLD
 ASIANOW
 U.S.
 LOCAL
 POLITICS
 WEATHER
 BUSINESS
 SPORTS
 TECHNOLOGY
   computing
   personal technology
   space
 NATURE
 ENTERTAINMENT
 BOOKS
 TRAVEL
 FOOD
 HEALTH
 STYLE
 IN-DEPTH

 custom news
 Headline News brief
 daily almanac
 CNN networks
 CNN programs
 on-air transcripts
 news quiz

  CNN WEB SITES:
CNN Websites
 TIME INC. SITES:
 MORE SERVICES:
 video on demand
 video archive
 audio on demand
 news email services
 free email accounts
 desktop headlines
 pointcast
 pagenet

 DISCUSSION:
 message boards
 chat
 feedback

 SITE GUIDES:
 help
 contents
 search

 FASTER ACCESS:
 europe
 japan

 WEB SERVICES:
Computing

From...

How to cut, copy, and paste in Java

September 17, 1998
Web posted at:

by Jean-Pierre Dube

(IDG) -- This article will give you a good understanding of how to send and get information from the clipboard in Java. You'll also learn how to deal with the different data flavors available. Finally, we'll cover the multiple personalities of clipboards and how they provide support for more than one data flavor.

Java offers two types of clipboards: local and system. Local clipboards are only available inside the virtual machine that your applet or application is running. However, unlike some operating systems that limit you to only one clipboard, Java allows you to have as many local clipboards as you desire. Accessing a particular local clipboard is as easy as referring to it by name.

System clipboards are directly linked with the peer operating system, allowing your application to transfer information among any applications running under that operating system. One disadvantage of using the system clipboard is that you can only transfer text data. Other types of objects are not supported by the system clipboard. With any luck, this issue will be addressed in the next release of the JDK.

Before we go any further, let's take a look at all the classes involved in manipulating the clipboard. These classes, listed in the table below, are all part of the java.awt.datatransfer package.

List of all classes in the java.awt.datatransfer package
NameTypeDescription
ClipboardClassDeals with everything that is a transferable
ClipboardOwnerInterfaceEvery class that deals with the clipboard must implement this interface. This interface is used to notify when the data originally placed in the clipboard has been overwritten
DataflavorClassRepresents all the data types that transferable support
StringSelection ClassOne type of transferable that is supplied with Java
TransferableInterfaceWrapper to objects passed to the clipboard
UnsupportedFlavor ExceptionClassException thrown by transferable for an unsupported data flavor

More on the clipboard classes
Let's go deeper into our exploration of the java.awt.datatransfer package by looking in detail at each class.

The Clipboard class
The Clipboard class is your link to accessing the clipboard. It includes three methods, which are defined in the following table:

Clipboard class
MethodDescription
String getName ()Get the name of the clipboard
void setContents (Transferable, ClipboardOwner)Set the content of the clipboard along with owner object
Transferable getContent (Object)Get the content of the clipboard in the form of a Transferable object. The object passed as a parameter is the owner

The three Clipboard class methods above allow you to name the clipboard, send information to it, or get information from it. Accessing the system clipboard or creating a local clipboard is different and requires a bit more discussion. To access the system clipboard, assign a reference from the system clipboard to the Clipboard class, such as:


Clipboard clipboard = getToolkit ().getSystemClipboard ();

On the other hand, to create a local clipboard you only need to create a Clipboard object with the name that you want to assign to it, for example:


Clipboard clipboard = new Clipboard ("My first clipboard");

Accessing the system clipboard or creating a local clipboard is different but straightforward.

MORE COMPUTING INTELLIGENCE
  IDG.net home page
  JavaWorld home page
 Reviews & in-depth info at IDG.net
    IDG.net's programming tools page
  IDG.net's Java page
  IDG.net's personal news page
  Subscribe to IDG.net's free daily newsletter for developers and technical experts
  Questions about computers? Let IDG.net's editors help you
  Search IDG.net in 12 languages
 News Radio
  Fusion audio primers
  Computerworld Minute
   

The ClipboardOwner interface
Because Java is a multiplatform language, and because operating systems behave differently toward clipboards, the authors of the Java language had to come up with a mechanism to deal with subtle differences. This is the reason for the presence of the ClipboardOwner interface. Its sole function is to inform the owner of the clipboard when his or her data is being overwritten by someone else. It can also signal an application when to release a resource associated with the data.

In a real application, the lostOwnership method could be used to set a flag that informs your application about the availability of the data in the clipboard. Microsoft Word, while not written in Java, is a good example of this mechanism at work in an application. Whenever you put something in the clipboard within Word and then quit, a dialog box appears informing you that data is in the clipboard. You will then be asked if you want to leave the data in the clipboard.

Implementing the ClipboardOwner interface is relatively straightforward because there is only one method to implement. This method will cause your program to relinquish ownership of the clipboard.

The DataFlavor class
The DataFlavor class is used to represent the type of an object. You're not limited to one data flavor (or type) per object. And, like us, your objects can have multiple personalities! For example, an image class can be represented as a Java class or as an array of bits (GIF, JPEG, and so on). In reality, a DataFlavor class is a wrapper to a MIME type. The MIME standard is extensive, hence there are virtually no limits to the data that can be transferred to the clipboard. (A discussion on the MIME standard is out of the scope of this article, but you can find additional information in the JavaWorld Resources section.

As an example of a data flavor, you will find that the StringSelection class has two flavors based on MIME types. On implementation is "application/x-java-serialized-object", and the second is "text/plain; charset=unicode". In fact, this implementation is telling us that we can retrieve text from the clipboard as a String class (application/x-java-serialized-object) or as plain text (text/plain; charset=unicode).

There are two ways to create a DataFlavor. You can write:


public DataFlavor (representationClass, String humanRepresentationName)

This constructor will create a new data flavor that represents a Java class. The returned DataFlavor will have representationClass = representationClass and a mimeType = application/x-java-serialized-object. As an example, the following would create a DataFlavor for the java.awt.Button:


DataFlavor (Class.forName ("java.awt.Button"), "AWT Button");

Now, this second constructor


public DataFlavor (String mimeType, String humanRepresentationName)

will construct a DataFlavor using a MimeType. The returned DataFlavor will be based on the MimeType. If the MimeType is application/x-java-serialized-object, then the result will be the same as if you called the previous constructor. Nonetheless, the returned DataFlavor will be representationClass= InputStream and mimeType =mimeType. As an example, the following call would create a plain-text flavor:


public DataFlavor ("text/plain; charset=unicode", "Unicode");

The following table shows the methods of the DataFlavor class.

DataFlavor class
MethodsDescription
boolean equals (DataFlavor)Test if the DataFlavor supplied is equal to the DataFlavor represented by this class
String getHumanPresentableName ()Return the human representable name for the format that this DataFlavor represents
void setHumanPresentableName (String)Set the human representation name for this DataFlavor
String getMimeType ()Get the MIME type string represented by this DataFlavor
Class getRepresentationClass ()Return the Class that represents this class

The Transferable interface
The Transferable interface must be implemented by all classes that you want to send to the clipboard, hence the Clipboard class will only understand classes that have been wrapped by the Transferable interface. The Transferable interface is comprised of three methods:

Transferable interface
MethodsDescription
DataFlavor getTransferDataFlavor ()Return an array of DataFlavor that represents the object
boolean isDataFlavorSupported (DataFlavor)Test if the DataFlavor supplied is supported
Object getTransferData (DataFlavor)Return the object represented by the supplied DataFlavor

This concludes our tour of all the classes involved in handling the clipboard. We have seen that in order to access the clipboard we must either create a Clipboard object or obtain a reference to the system clipboard. Because the clipboard only accepts objects of type Transferable, the object that you want to send to the clipboard must implement this interface. Finally, all objects in the clipboard have flavors that are represented by the DataFlavor class, which in reality is a wrapper to MIME types.

In the next sections, we will put into practice what we have learned.

The recipe for clipboard utilization
How these various classes access the clipboard can be confusing. Fortunately, there is a simple recipe, which involves the following steps:

Step 1. Create a class called xxxxSelection. Here, xxx should name the type represented by this flavor. For example, ImageSelection would be a good name for an image flavor. This naming convention is merely a suggestion, of course. I'm following the established convention of use with the StringSelection provided in the JDK, but you can name this class anything you want. It's important to remember that this object must implement the Transferable and ClipboardOwner interfaces. If you are planning to transfer text, the StringSelection class should be used instead.

Step 2. Define a class to access the clipboard. To access a local clipboard, use the following call: Clipboard clipboard = new Clipboard ("name"). To access the peer operating system clipboard, use this call instead: Clipboard clipboard = getToolkit ().getSystemClipboard ().

Step 3. Set the content of the clipboard. To do this, use the setContent method in the Clipboard class, where the first parameter is an object that implements a Transferable (xxxxSelection class created in Step 1), and the second parameter is a reference to the class calling this method.

Step 4. Get the content of the clipboard. Use the getContent method in the Clipboard class. This method will return a class of type Transferable.

Step 5. Implement a 'cut operation'. To do this, you must manually erase the data once it is copied to the clipboard. Java provides no implementation of a cut operation.

Conclusion
In this tip, we have seen that in order to use the clipboard we need a Clipboard object. Also, data sent to the clipboard must implement the Transferable interface. And all data in the clipboard must have one or more flavors that are defined by the DataFlavor class.

Related stories:
Latest Headlines

Today on CNN

Related IDG.net stories:

Note: Pages will open in a new browser window Related sites:

External sites are not
endorsed by CNN Interactive.

SEARCH CNN.com
Enter keyword(s)   go    help

  
 

Back to the top
© 2000 Cable News Network. All Rights Reserved.
Terms under which this service is provided to you.
Read our privacy guidelines.