Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JavaFX KeyCombination with three or more keys?

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 MenuItems 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.

like image 575
Daniel Kvist Avatar asked Mar 15 '15 18:03

Daniel Kvist


2 Answers

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

like image 142
Marcel Avatar answered Oct 27 '22 00:10

Marcel


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();
            }
        }
        );
like image 37
Amit Lohar Avatar answered Oct 26 '22 23:10

Amit Lohar