Java Get Clipboard

Clipboard provides application to transfer data. Here, we have used Swing and AWT package to illustrates you the use of method getSystemClipboard().

Java Get Clipboard

Clipboard provides application to transfer data. Here, we have used Swing and AWT package to illustrates you the use of method getSystemClipboard().

Java Get Clipboard

Java Get Clipboard

     

In this section, you will study how to use the method getClipboard().

Clipboard provides application to transfer data. Here, we have used Swing and AWT package to illustrates you the use of method getSystemClipboard(). In this example, you can copy and paste the text on the text field. 

The method getSystemClipboard() provides the clipboard facilities to transfer data. The method area.getSelctedText() returns the selected text of the text component. This selected text is then add to the clipboard using the method clipboard.setContents(). The method getClipboardContents() get the contents added to the clipboard. Then using the class Transferable the content of the clipboard get transfered using the method getTransferData(). The method replaceSelection() returns the selected text.

 

Here is the code of GetClipboard.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.datatransfer.*;

public class GetClipboard {
  public static void main(String args[]) {
  JFrame frame = new JFrame("Use Clipboard");
  final Clipboard clipboard =
  frame.getToolkit().getSystemClipboard();
  final JTextArea area = new JTextArea();
  frame.add(area, BorderLayout.CENTER);
 JButton copy = new JButton("Copy");
 copy.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
  String selection = area.getSelectedText();
  StringSelection data = new StringSelection(selection);
  clipboard.setContents(data, data);
  }
  });
 JButton paste = new JButton("Paste");
 paste.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent actionEvent) {
  Transferable clipData = clipboard.getContents(clipboard);
  try {
  if(clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) {
  String s = (String)(clipData.getTransferData(DataFlavor.stringFlavor));
  area.replaceSelection(s);
  }
  } catch (Exception ufe) {}
  }
  });
  JPanel p = new JPanel();
  p.add(copy);
  p.add(paste);
  frame.add(p, BorderLayout.SOUTH);
  frame.setSize(300, 200);
  frame.setVisible(true);
  }
}

 

Output will be displayed as:

 

Download Source Code