Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-get-example Java Get Clipboard

Related Tutorials


 
 

Share on Google+Share on Google+

Java Get Clipboard

Advertisement
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

     

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

 

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2008

Related Tutorials

Discuss: Java Get Clipboard  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com