从javafx应用程序复制图像并使用窗口功能粘贴它

时间:2013-12-10 10:18:17

标签: java javafx javafx-2 fxml javafx-8

我正在研究javafx应用程序。我想使用上下文菜单从应用程序复制图像,然后使用粘贴的Windows功能粘贴它。

 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);
        }
    });

示例,如下图所示。

Copy Image From aaplication

想要使用窗口功能菜单粘贴到位置。

Paste Image at spectific location

1 个答案:

答案 0 :(得分:3)

使用ClipboardClipboardContent,例如为:

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);

要使Windows上下文菜单的“粘贴”操作起作用,剪贴板内容必须为File。在上面演示的情况下,这很容易,否则应该创建一个临时文件。