Listening on system clipboard using JavaFx

2019-08-05 04:15发布

问题:

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.