How can I add a function key (i.e. the F1 to F12 keys) for shortcut key in JavaFX? I use save button. I don’t need to click save button and it make easy to system
1 Answer
If you are using a Button, let's say saveButton and it is in Scene scene then you can set accelerator(shortcut key) to button as following:
Button saveButton = new Button("save");
scene.getAccelerators().put(new KeyCodeCombination(KeyCode.F1), saveButton::fire);
KeyCodeCombination in above code is used to set accelerators to javaFX contols and It takes, as argument, KeyCode e.g. KeyCode.K, KeyCode.F3 etc. and/or KeyCombination like KeyCombination.SHORTCUT_DOWN etc.
and if you are using MenuItem let's say saveMenu then you can set accelerator(shortcut key) to it as following:
MenuItem saveMenu = new MenuItem("save");
saveMenu.setAccelerator(new KeyCodeCombination(KeyCode.F1));