How do I cut and past text from the clipboard?

John Zukowski

Starting with Java 1.1, access to the system clipboard is available via the java.awt.datatransfer package. This package also provides the basis for drag-and-drop capabilities, which is included with Java in the 1.2 release (in the java.awt.dnd package).

The Clipboard class is the basis for the capabilities. By asking the Toolkit, you can access the system clipboard with the Toolkit.getSystemClipboard() method. This requires a check past the SecurityManager so is usually restricted within applets. In both applets and applications you can create a Clipboard independent of the system clipboard by just calling the constructor for Clipboard. This way, applets can still provide cut-and-paste capabilities internally, without accessing the system's clipboard, and applications can maintain a private clipboard as well as accessing the system clipboard.

Items are placed on the clipboard with the Clipboard.setContents() method. This requires that the items implement the Transferable interface.

public interface Transferable {
  public abstract DataFlavor
  public abstract boolean
  public abstract Object

The Transferable interface works with items that can be represented in different DataFlavors. Essentially, flavors are MIME types and may be represented by the standard MIME type strings. The getTransferDataFlavors() method returns flavors ordered from richest to simplest (i.e., MS Word, RTF, ASCII). Also, an additional MIME type was introduced to represent Java classes:

application/x-java-serialized-object; class=classname
application/x-java-serialized-object; class=java.util.Vector

Because transferring text is so common, Java provides the StringSelection class to assist. There is one limitation with information sent to the system clipboard: between Java programs and non-Java programs, you can only transfer text strings.

Clipboard Access Example

The following program demonstrates the use of all these classes. If there is a command line argument, it places it on the clipboard. Then, it takes off whatever is on the clipboard, as a String, and prints it out. If the contents cannot be represented as a String the exception message String is caught and displayed.

import java.awt.Toolkit;
import java.awt.datatransfer.*;
public class clip {
  public static void main (String args[]) {
    Clipboard clipboard = 
    if (args.length != 0) {
      StringSelection data =
        new StringSelection (args[0]);
      clipboard.setContents (data, data);
    Transferable clipData = 
    String s;
    try {
      s = (String)(clipData.getTransferData(
    } catch (UnsupportedFlavorException ee) {
      s = ee.toString();
    System.out.println ("Clipboard Had: " + s);
    System.exit (0);
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact