0

I'm trying to make my program in JavaFX do something when I hold down the Shift key. When I do so, I only get one KEY_PRESSED event, but when I hold down another button like "a". It works fine and I get multiple KEY_PRESSED events. How do I fix this?

Here is the code:

public void keyPressed(KeyEvent keyEvent) {
    System.out.println(keyEvent.getEventType());
}

The fxml file where I call the method:

<GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onKeyPressed="#keyPressed" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.drawController">

EDIT: I figured it out. If I use the isShiftDown() I get a single true, but nothing more. However, I realized that if I call the function on KEY_RELEASED as well isShiftDown() will return false so just waiting for it to turn false solved my issue.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [JavaFX : How to detect if a key is being held down?](https://stackoverflow.com/questions/26917566/javafx-how-to-detect-if-a-key-is-being-held-down) – Scott Mar 18 '21 at 12:02
  • 1
    You may also want to have a look at the `KeyEvent.isShiftDown()` function – Scott Mar 18 '21 at 12:05
  • What about other modifier keys ctrl etc? You might need to keep track of the state of the shift key, when it is pressed start a repeating action and when it is released stop the repeating action. – matt Mar 18 '21 at 12:05
  • `KeyEvent.isShiftDown()` only gives true one time as well and does not return false when i let go if its even supposed to do that – Isak Holmström Mar 18 '21 at 12:31
  • 5
    This is probably intended behavior for modifier keys, not a bug in JavaFX. And that's assuming JavaFX is responsible for this behavior instead of the operating system or even the keyboard itself. So I don't believe there will be a way to make multiple key-pressed events fire when you hold down shift. However, you can try the solution suggested by Matt: Trigger a [repeating action](https://stackoverflow.com/questions/9966136/javafx-periodic-background-task/60685975#60685975) on the key-pressed event and stop that action on the key-released event. – Slaw Mar 18 '21 at 13:19
  • 3
    I think this is expected. The repeated key press events you see on character keys comes from the native system. You probably don't want to rely on that anyway; at best you cannot rely on the timing being the same on all systems, at worst it may not even occur on some systems. – James_D Mar 18 '21 at 13:37

0 Answers0