0

I want to filter some characters i.e. the letter "a" in a TextField. I explicitly don't want to use the recommended TextFormatter / setTextFormatter() for this task.

The code sample below should actually consume the event on the event-dispatching chain before it arrives to the TextField node, which is a child node of parentNode, but it doesn't. Same happens if I set the filter on the textfield node itself of course.

Why?

    parentNode.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
        if (event.getCode() == KeyCode.A) {
            event.consume();
        }
    });
Andy
  • 488
  • 4
  • 13
  • _ I explicitly don't want to use the recommended TextFormatter_ why not? – kleopatra May 08 '21 at 12:56
  • cause i want to understand event processing lol, thats why. Using TextFormatter is easy in this example but not the issue ... – Andy May 08 '21 at 13:18
  • ahh, I see, but then your answer doesn't really help you (in fully understanding the event processing :) Anyway, you should edit your question: academic excercises are perfectly valid but if a question is about them, it should be stated clearly in the question – kleopatra May 08 '21 at 13:19
  • thats why I wrote "understand event processing" and NOT "fully". Reading questions/ comments thoroughly prevents unnecessary discussions ... ;-) – Andy May 08 '21 at 13:23

1 Answers1

0

ah, really strange, seems like KeyEvent.KEY_PRESSED is not sufficient to handle all dispatched events. If I use the more generic KeyEvent.ANY instead the following code works:

    TextField tf = new TextField();
    tf.addEventFilter(KeyEvent.ANY, event -> {
        if (event.getCharacter().matches("[aA]"))
            event.consume();
    });
Andy
  • 488
  • 4
  • 13
  • you don't need `ANY` but the type that generates input, that is represents a char ;) – kleopatra May 08 '21 at 13:48
  • give me code example please, so I can see what you mean ,thx. – Andy May 08 '21 at 14:31
  • 2
    Text input controls use `KEY_TYPED` for character input, since that's the only event type where [`getCharacter()`](https://openjfx.io/javadoc/16/javafx.graphics/javafx/scene/input/KeyEvent.html#getCharacter()) returns something meaningful. Though it uses `KEY_PRESSED` for other key events, such as backspace, enter, arrow keys, and so on. You can see the event handling code in the internal behavior class: https://github.com/openjdk/jfx/blob/master/modules/javafx.controls/src/main/java/com/sun/javafx/scene/control/behavior/TextInputControlBehavior.java#L107 – Slaw May 08 '21 at 20:36