Listening on system clipboard using JavaFx

岁酱吖の 提交于 2019-12-11 06:28:50

问题


As stated in the answer to this question, one can setup a Timeline to check whether there is a change in the system clipboard:

Set and use variables outside timeline in javafx 8

But is there a better way? For example, an event listener? I have searched JavaFx 8 doc and didn't find anything obviously helpful.

Solutions using JavaFx is preferred, but all answers are welcome.


回答1:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.Clipboard;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        final Clipboard systemClipboard = Clipboard.getSystemClipboard();

        new com.sun.glass.ui.ClipboardAssistance(com.sun.glass.ui.Clipboard.SYSTEM) {
            @Override
            public void contentChanged() {
                System.out.print("System clipboard content changed: ");
                if ( systemClipboard.hasImage() ) {
                    System.out.println("image");
                } else if ( systemClipboard.hasString() ) {
                    System.out.println("string");
                } else if ( systemClipboard.hasFiles() ) {
                    System.out.println("files");
                }
            }
        };

        primaryStage.setScene(new Scene(new StackPane()));
        primaryStage.show();
    }

}

Test:

  • Press key Print Screen
  • Ctrl+C for selected string
  • Ctrl+c for selected files



回答2:


No, there isn't a better way. There are no events sent round when the clipboard contents change (especially if it's from outside of the Java application) and so only a polling approach is appropriate.



来源:https://stackoverflow.com/questions/25098813/listening-on-system-clipboard-using-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!