Java Swing clipboard FAQ: How do I copy an image to the clipboard in a Java/Swing application?
Last night I needed to do just this, get an image that I'm currently displaying in a Java JFrame, and copy that image to the clipboard. I won't discuss the solution here too much, other than to say that in the example source code below, a MetaFrame is a customized subclass of a JFrame, and when I call the getCurrentImage() function, it simply returns a Java Image type.
Here's the source code:
/** * COPY TO CLIPBOARD * ---------------------------------------------------------------------------------- * Steps to take when the user requests the current image is copied to the clipboard. */ public void doCopyToClipboardAction() { // figure out which frame is in the foreground MetaFrame activeMetaFrame = null; for (MetaFrame mf : frames) { if (mf.isActive()) activeMetaFrame = mf; } // get the image from the current jframe Image image = activeMetaFrame.getCurrentImage(); // place that image on the clipboard setClipboard(image); } // code below from exampledepot.com //This method writes a image to the system clipboard. //otherwise it returns null. public static void setClipboard(Image image) { ImageSelection imgSel = new ImageSelection(image); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null); } // This class is used to hold an image while on the clipboard. static class ImageSelection implements Transferable { private Image image; public ImageSelection(Image image) { this.image = image; } // Returns supported flavors public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } // Returns true if flavor is supported public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } // Returns image public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (!DataFlavor.imageFlavor.equals(flavor)) { throw new UnsupportedFlavorException(flavor); } return image; } }
The actual solution to this problem comes from the excellent Example Depot website, specifically this clipboard example. All I had to do was call the setClipboard
method, and it handled the process of copying the image to the clipboard.
As you can see from their source code, Java classes and interfaces you need to know about in this solution are:
- Transferable
- DataFlavor
- ImageSelection
- Toolkit, and the getSystemClipboard method
I tested this code last night, and it works as advertised, copying an Image (a BufferedImage in my case) to the Mac clipboard, after which I could then paste the image into other Mac applications.
I hope seeing this solution in this context helps, but again, all the thanks for the solution goes to the Example Depot website.