Copy & Paste

Copy & Paste

How can I copy the selected text from a TextArea to the system clipboard or paste from the system clipboard to a TextArea?

Java 1.1 introduced the java.awt.datatransfer package, which implements the basic mechanisms for using the system clipboard. It defines a Clipboard class through which you can cut and paste arbitrary data. To access the system clipboard, you first need to get a reference to the default system toolkit with Toolkit.getDefaultToolkit(). Then you can retrieve a Clipboard instance representing the system clipboard by calling getSystemClipboard().Now that you have a reference to the system clipboard, all you have to do to implement a copy operation is to fetch the selected text from the TextArea, and set the clipboard contents. TextArea selections are accessed with getSelectedText() and Clipboard contents are set with setContents(). As you can see, a lot of Java programming just involves knowing which methods to call and what they do. Pasting from the clipboard involves retrieving its contents with getContents() and inserting the text into the TextArea at the current cursor position. The accompanying program demonstrates how to perform these operations.

Of special note is that not all window systems posses the same notion of a system clipboard. The X Window system only maintains the concept of a current selection, without requiring a cut and paste operation. The instant a piece of text is selected, it becomes eligible for pasting. Windows 95 and the Mac require you to cut or copy a selection before it can be pasted. The system clipboard example program will only function as expected in a cut and paste window environment. In the X Window system, a Java program usingnative peer widgets like java.awt.TextArea, will automatically handle selection copying through the native window system, and the techniquesin the example become nonapplicable.

import java.awt.*;import java.awt.event.*;import java.awt.datatransfer.*;public final class ClipboardExample extends Frame {  private TextArea __textArea;  private Button __copyButton, __pasteButton;  private Clipboard __systemClipboard;  public ClipboardExample() {    super("Clipboard Demo");    ActionListener copyListener, pasteListener;    __systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();    __textArea = new TextArea("Start typing!");    __textArea.setColumns(30);    __textArea.setRows(20);    __textArea.setEditable(true);    __copyButton  = new Button("Copy");    __pasteButton = new Button("Paste");    copyListener = new ActionListener() {      public void actionPerformed(ActionEvent event) {	String selection;	StringSelection stringSelection;	selection = __textArea.getSelectedText();	if(selection == null)	  selection = "";	stringSelection = new StringSelection(selection);	__systemClipboard.setContents(stringSelection, stringSelection);      }    };    pasteListener = new ActionListener() {      public void actionPerformed(ActionEvent event) {	Transferable contents;	String selection;	contents = __systemClipboard.getContents(null);	try {	  selection = 	    (String)contents.getTransferData(DataFlavor.stringFlavor);	  System.out.println("FOO");	  System.out.println(selection);	  __textArea.insert(selection, __textArea.getCaretPosition());	} catch(UnsupportedFlavorException ufe) {	  ufe.printStackTrace();	} catch( ioe) {	  ioe.printStackTrace();	}      }    };    __copyButton.addActionListener(copyListener);    __pasteButton.addActionListener(pasteListener);    setLayout(new BorderLayout());    add(__textArea, BorderLayout.CENTER);    add(__copyButton, BorderLayout.NORTH);    add(__pasteButton, BorderLayout.SOUTH);  }  public static void main(String[] args) {    ClipboardExample example;    WindowListener exitListener;    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {	Window window = e.getWindow();	window.setVisible(false);	window.dispose();	System.exit(0);      }    };    example = new ClipboardExample();    example.addWindowListener(exitListener);    example.pack();    example.setVisible(true);  }}

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist