Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Use Java to Interact with Your Clipboard : Page 5

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.


WEBINAR: On-Demand

Unleash Your DevOps Strategy by Synchronizing Application and Database Changes REGISTER >

Grabbing an Image from the Clipboard
The ImageGrabber class in the sample code shows how to grab an image from the system clipboard and then display it using the Viewer class. The method getImageFromClipboard takes on the bulk of the work by grabbing the clipboard contents. The clipboard contents are grabbed from the system Clipboard object and stored in a Transferable object the same way that was done with the TextGrabber class. If it turns out that the clipboard contents are something that fall under the umbrella of image formats supported by the imageFlavor Flavor, then you go ahead and caste your Transferable object to an Image object.

public static Image getImageFromClipboard() { // 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 contents are empty, if so, return null if (clipboardContents == null) return null; else try { // make sure content on clipboard is // falls under a format supported by the // imageFlavor Flavor if (clipboardContents .isDataFlavorSupported( DataFlavor.imageFlavor)) { // convert the Transferable object // to an Image object Image image = (Image) clipboardContents .getTransferData(DataFlavor.imageFlavor); return image; } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return null; }

The ImageGrabber class' main method passes the Image object retrieved from the system clipboard on to the Viewer class for displaying to the user.

To test the ImageGrabber class out, you can go to your favorite image viewing software and copy a GIF or JPEG image to the clipboard. Then execute the ImageGrabber class. If things are working correctly, you should see the image displayed.

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