Browse DevX
Sign up for e-mail newsletters from DevX


Use Java to Interact with Your Clipboard : Page 3

These days end users expect to use the ubiquitous "clipboard" concept as a transfer station for data, and if your applications don't support it, users won't be pleased. Learn how to use the java.awt.datatransfer package to cut, copy, and paste to a clipboard in Java.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Let's See Some Code!
This text-based example grabs text from the clipboard and then writes to it.

The downloadable sample code provided with this article contains the class TextGrabber, which is shown below. Test the code out by opening up Notepad. Type a small text message and copy the message to your clipboard using Ctrl-C as you normally would copy text. When you execute the class, you should see that the class echoes what you placed on the clipboard.

public class TextGrabber { public static String getClipboard() { // get the system clipboard Clipboard systemClipboard = Toolkit .getDefaultToolkit() .getSystemClipboard(); // get the contents on the clipboard in a // transferable object Transferable clipboardContents = systemClipboard .getContents( null); // check if clipboard is empty if (clipboardContents == null) { return ("Clipboard is empty!!!"); } else try { // see if DataFlavor of // DataFlavor.stringFlavor is supported if (clipboardContents .isDataFlavorSupported( DataFlavor .stringFlavor)) { // return text content String returnText = ( String) clipboardContents .getTransferData( DataFlavor .stringFlavor); return returnText; } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return null; } public static void main(String[] args) { System.out.println( "Copying text from system clipboard."); String grabbed = getClipboard(); System.out.println(grabbed); } }

In the code above, the system clipboard is a Clipboard object, which then uses the getContents method of the object to return the contents of the clipboard as a Transferable object. From there, make sure to support the predefined flavor of DataFlavor.stringFlavor (a Flavor innate in the DataFlavor object, which represents a Java Unicode String class). After confirming support for DataFlavor.stringFlavor, use the getTransferData method of the clipboard object, passing to it the argument of the DataFlavor.stringFlavor DataFlavor. This yields the clipboard text which returns as a String to the calling method.

Comment and Contribute






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



Thanks for your registration, follow us on our social networks to keep up-to-date