user2799603
user2799603

Reputation: 923

JavaFX key listener for multiple keys pressed implementation?

I would like to create an event handler that listens for multiple key combinations such as holding Ctrl and C at the same time.

Why doesn't something like if((... == Control) && (... == C)) work?

Here is the code I trying to work with:

textField.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent event) {
        if ((event.getCode() == KeyCode.CONTROL) && (event.getCode() == KeyCode.C)) {
            System.out.println("Control pressed");
        } 
    };
});

Upvotes: 3

Views: 9383

Answers (4)

malamut
malamut

Reputation: 465

A bit more concise (avoids new KeyCombination()):

public void handle(KeyEvent event) {
    if (event.isControlDown() && (event.getCode() == KeyCode.C)) {
        System.out.println("Control+C pressed");
    } 
};

There are methods of the type KeyEvent.isXXXDown() for the other modifier keys as well.

Upvotes: 0

mtrgn
mtrgn

Reputation: 131

You can try this solution, it worked for me!

final KeyCombination keyCombinationShiftC = new KeyCodeCombination(
KeyCode.C, KeyCombination.CONTROL_DOWN);

textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        if (keyCombinationShiftC.match(event)) {
            logger.info("CTRL + C Pressed");
        }
    }
});

Upvotes: 6

Anshul Parashar
Anshul Parashar

Reputation: 3126

One way to tackle this problem is to create a KeyCombination object and set some of its properties to what you see below.

Try the following:

textfield.getScene().getAccelerators().put(new KeyCodeCombination(
    KeyCode.C, KeyCombination.CONTROL_ANY), new Runnable() {
    @Override public void run() {
        //Insert conditions here
        textfield.requestFocus();
    }
});

Upvotes: 5

WonderWorld
WonderWorld

Reputation: 966

This would be of some help. KeyCombination.

final KeyCombination keyComb1=new KeyCodeCombination(KeyCode.C,KeyCombination.CONTROL_DOWN);

https://code.google.com/p/javafx-demos/source/browse/trunk/javafx-demos/src/main/java/com/ezest/javafx/demogallery/KeyCombinationDemo.java?r=27

Upvotes: 1

Related Questions