简体   繁体   中英

Disable character removing keys in a JavaFX TextField

The title pretty much says it all. I need to disable character-removing keys in a JavaFX TextField. By character-removing keys, I mean DEL and SUPPR.

Right now, this is what I have:

mytextfield.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
        public void handle(KeyEvent event) {          
            if (event.getCharacter().matches("[0-9]")) {
                // some stuff that works perfectly here
            }
            event.consume(); // to cancel everything but 0-9 keys
        }
    });

But for some reason, even though the event gets consumed, the end character still gets deleted when pressing delete.

Thanks for your time!

KEY_TYPED will fire an event only after pressing a key that generates a UTF output. KEY_TYPED event will not be generated at BACK_SPACE and DELETE key press. Use the KEY_PRESSED event instead.

mytextfield.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        public void handle(KeyEvent event) {          
            if (event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE) {
                event.consume(); // to cancel character-removing keys               
            }
        }
    });

Putting the event.consume() inside the if block will cancel only these buttons. The others will work as usual.

This worked fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM