Andy
Andy

Reputation: 518

Why consume() on a KeyEvent in an event filter not working?

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();
        }
    });

Upvotes: -1

Views: 581

Answers (1)

Andy
Andy

Reputation: 518

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();
    });

Upvotes: 0

Related Questions