Skip to content
Advertisement

Copy image from JavaFX application and paste it using Windows

I am working on a JavaFX application. I want to copy image from application using context menu and paste it using Windows feature of paste.

 File file = new File("C:\Users\Admin\Desktop\my\mysql.gif");
    Image image = new Image(file.toURI().toString());
    ImageView ive =new ImageView(image);
    cm = new ContextMenu();
 MenuItem copy = new MenuItem("Copy");
 cm.getItems().add(copy);
 copy.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent t) {
            //Paste Image at location
            Clipboard clipboard = Clipboard.getSystemClipboard();
            ClipboardContent content = new ClipboardContent();
            content.putImage(image); // the image you want, as javafx.scene.image.Image
            clipboard.setContent(content);
        }
    });

For example, like shown below in images.

Copy Image From aaplication

And want to paste at location from using of Windows features menu.

Paste Image at spectific location

Advertisement

Answer

Use the Clipboard and ClipboardContent, e.g. as:

Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
// for paste as image, e.g. in GIMP
content.putImage(image); // the image you want, as javafx.scene.image.Image
// for paste as file, e.g. in Windows Explorer
content.putFiles(java.util.Collections.singletonList(new File("C:\Users\Admin\Desktop\my\mysql.gif")));
clipboard.setContent(content);

For the “Paste” operation of Windows context menus to work, the clipboard content has to be File. In the case demonstrated above, this is easy, otherwise a temporary file should be created.

Advertisement