I'm creating a simple text editor with JavaFX.
I've found out that I can add shortcuts to menu items by using
MenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+S"))
I'm going to use this for the frequently used MenuItem
s in my application, such as Save, Open etc. This works fine as long as I only use two keys, for example Ctrl+S, but I also want to create some combinations with three keys, such as for the Save All option, which in many programs has the shortcut Ctrl+S+A (Same as for Save, but with an extra A, which logically stands for All).
This brings a problem.
JavaFX doesn't let me use more than two keys with the KeyCombination.keyCombination(String)
method. I just get an error when I run the application.
I've used Google, as always, but I can't find anything about using more than two keys, so I decided to ask a question here.
I wonder how I can set more than two keys (I currently require three) as a shortcut for a MenuItem
in JavaFX.
The Problem is that the KeyEvent only has one KeyCode. So its not possible to let an KeyCombination match multiple KeyCodes.
But you can try something like this:
Store all pressed Keys into an List (maybe you have to use event Listener for keyPressed)
@Override
public void initialize(URL location, ResourceBundle resources) {
scene.setOnKeyPressed((event) -> {
codes.add(event.getCode());
});
scene.setOnKeyReleased((event) -> {
codes.remove(event.getCode());
});
}
Write your own KeyCombi class
private class MultipleKeyCombi extends KeyCombination {
private List<KeyCode> neededCodes;
public MultipleKeyCombi(KeyCode... codes) {
neededCodes = Arrays.asList(codes);
}
@Override
public boolean match(KeyEvent event) {
return codes.containsAll(neededCodes);
}
}
And use it in your Menu.
item.setAccelerator(new MultipleKeyCombi(KeyCode.A, KeyCode.S));
This should work.
I wrote a Prototype here Bitbucket Repo
I am also new to JavaFX, I have done the following code and it works!
primaryStage.getScene().getAccelerators().put(
KeyCombination.keyCombination("CTRL+SHIFT+U"),
new Runnable() {
@Override
public void run() {
System.out.println("Keycombination Detected");
Platform.exit();
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With