Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javafx keyboard event shortcut key

Tags:

javafx

keycode

I want to add keyboard shortcut key in javafx.

i have scene and want to implement the keyboard shortcut

my code is as follows

getApplication().getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {

        public void handle(KeyEvent ke) {
            if (ke.getCode() == KeyCode.ESCAPE) {
                System.out.println("Key Pressed: " + ke.getCode());
            }
        }
    });
like image 793
Himanshu verma Avatar asked Aug 20 '14 06:08

Himanshu verma


People also ask

What is key combination?

Represents a combination of keys which are used in keyboard shortcuts. A key combination consists of a main key and a set of modifier keys.

How do I set hotkeys in Eclipse?

the main preference page can be found under window > preferences > general > keys (or faster: press ctrl+3 , type keys and press enter ). from here you can see all commands and assign/change their associated keyboard shortcuts.

How do I add a keyboard shortcut in Visual Studio?

Customize a keyboard shortcutOn the menu bar, choose Tools > Options. Expand Environment, and then choose Keyboard.


1 Answers

Events travel from the scene to the focused node (event capturing) and then back to the scene (event bubbling). Event filter are triggered during event capturing, while onKeyPressed and event handler are triggered during event bubbling. Some controls (for example TextField) consume the event, so it never comes back to the scene, i.e. event bubbling is canceled and onKeyPressed for the scene doesn't work.

To get all key pressed events use addEventFilter method:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.ESCAPE) {
            System.out.println("Key Pressed: " + ke.getCode());
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});

If you want to capture key combinations use the KeyCodeCombination class:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    final KeyCombination keyComb = new KeyCodeCombination(KeyCode.ESCAPE,
                                                          KeyCombination.CONTROL_DOWN);
    public void handle(KeyEvent ke) {
        if (keyComb.match(ke)) {
            System.out.println("Key Pressed: " + keyComb);
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});

There is also the possibility to add shortcuts to the menu by setting an accelerator (see [2]).

References

  • [1] http://docs.oracle.com/javafx/2/events/processing.htm
  • [2] https://blog.idrsolutions.com/2014/04/tutorial-how-to-setup-key-combinations-in-javafx/
like image 68
user2229691 Avatar answered Sep 21 '22 23:09

user2229691