0

KeyEvent.consume does not work in JavaFX.

I’m new to JavaFX (coming from using Swing) and I’m trying to make a program that blocks certain characters from being typed into a TextField. Now in Swing I could use a KeyListener and use event.consume(); to prevent the event from being processed and typed into the JTextField. But in the JavaFX’s EventHandler while KeyEvent does have a consume method it does not work and the character is still typed into the TextField. Here is the code for the TextField EventHandler.

input1TextField.setOnKeyTyped(new EventHandler<KeyEvent>() {

    @Override
    public void handle(KeyEvent event) {
        System.out.println(event.getCharacter());
        event.consume();//this does not work
    }
});
Abra
  • 19,142
  • 7
  • 29
  • 41
user3491432
  • 91
  • 2
  • 7
  • 4
    _in swing I could use a KeyListener and use event.consume()_ Better to use a [document filter](https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter). In JavaFX, you should use a [text formatter](https://stackoverflow.com/questions/40472668/numeric-textfield-for-integers-in-javafx-8-with-textformatter-and-or-unaryoperat) – Abra Oct 29 '22 at 08:40
  • 3
    JavaFX is not the same as *Swing* and you can't write JavaFX applications the same way you write *Swing* applications and that includes [event handling](https://docs.oracle.com/javase/8/javafx/events-tutorial/events.htm#JFXED117) code. – Abra Oct 29 '22 at 08:56
  • 1
    High level nodes (i.e. controls such as `TextField`) already implement fairly complex behavior internally, via event listeners for low-level events such as mouse and key events. Implementing your own listeners for these low-level events is not robust, because it relies on how the internal key handling is implemented. You don't know if the text field processes `KEY_TYPED`, `KEY_PRESSED`, or `KEY_RELEASED` events, or whether it processes them with event handlers or event filters. On the other hand, the text formatter approach is specified and supported by the API; thus it is the correct approach – James_D Oct 30 '22 at 05:15

0 Answers0