javajavafx

Javafx table copy/paste listener


What's the proper way of listening to copy/paste commands on a Javafx table?

I don't want to just listen for Ctrl+C keys because the user may be in a Mac.

Edit: Also, windows 11 now uses both Ctrl+C and Ctrl+INSERT for copying. How can I handle that without checking OS and creating additional key listeners for Windows 11?


Solution

  • For copy/paste with the keyboard, JavaFX supports a semantic "shortcut" modifier, which is equivalent to "control" on Windows and Linux or "Meta" (also called "Command") on Mac. This is described in the documentation for KeyCombination:

    The shortcut modifier is used to represent the modifier key which is used commonly in keyboard shortcuts on the host platform. This is for example control on Windows and meta (command key) on Mac. By using shortcut key modifier developers can create platform independent shortcuts. So the "Shortcut+C" key combination is handled internally as "Ctrl+C" on Windows and "Meta+C" on Mac.

    You can use this when handling key events using KeyEvent.isShortcutDown() or in accelerators or mnemonics using, e.g. new KeyCodeCombination(KeyCode.C, KeyCombination.SHORTCUT_DOWN).


    Edit in response to

    Edit: Also, windows 11 now uses both Ctrl+C and Ctrl+INSERT for copying. How can I handle that without checking OS and creating additional key listeners for Windows 11?

    As far as I am aware there is no general "Is this action a platform COPY action" API in JavaFX. I don't have a Windows machine to test (or, indeed, a Mac keyboard with an "INSERT" key), but I think for the text input controls Shortcut+INSERT is implemented as "copy" and Shift+INSERT is implemented as "paste", on all platforms.

    You can see how the text input controls implement keyboard handling here. Essentially, different input mappings are created for each key combination that maps to each handler, and a central event handler uses the mapping to determine the action when a key event occurs. (So there is a separate input mapping for Ctrl+C and Ctrl+INSERT, both mapping to the same action.) Note these behavior classes are not part of the public API, which makes it pretty difficult to modify behaviors in JavaFX.