Copy & Paste

Copy & Paste

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

Answer:
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(java.io.IOException 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);  }}
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes