Search code examples
javajavafxcopy-paste

Listening for and injecting paste operations cross platform


Primary Question

I'd like to intercept paste operations into my JavaFX app (in a HTMLEditor specifically) to I can sanitize what a user can enter. Right now I'm able to intercept the command in windows using the following:

//In the initalize method of an HTMLEditor
super.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
    if(e.isControlDown() && e.getCode() == KeyCode.V) {
        modifyClipboardForNextPaste();
    }
});

But the paste command for OSX is "command + v" so this does not pick up those commands. Is there some type of filter I can add that picks up the paste event itself and not the keys that may or may not be bound to the paste event on the OS?

Related question:

I'm also trying to inject the paste command when a user selects a paste option on a context menu I'm making using the following code:

Robot robot = new Robot();
robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
robot.keyPress(java.awt.event.KeyEvent.VK_V);
robot.keyRelease(java.awt.event.KeyEvent.VK_V);
robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);

This has the same issue as above where OSX user or users who modified their paste commands do not get this.


Solution

  • The comments above have already answered the question. I am adding the actual code as a convenience here:

    import javafx.scene.input.Clipboard;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    
    public void enablePaste() {
      super.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
        if(e.isShortcutDown() && e.getCode() == KeyCode.V) {
          Clipboard clipboard = Clipboard.getSystemClipboard();
          // your action here e.g.      
          // if (clipboard.hasUrl()) {
          //  
          //}
        }
      });
    }