Reputation: 923
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
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
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
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
Reputation: 966
This would be of some help. KeyCombination.
final KeyCombination keyComb1=new KeyCodeCombination(KeyCode.C,KeyCombination.CONTROL_DOWN);
Upvotes: 1