禁用JavaFX TextField中的字符删除键 [英] Disable character removing keys in a JavaFX TextField

查看:51
本文介绍了禁用JavaFX TextField中的字符删除键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎说明了一切.我需要在JavaFX TextField中禁用字符删除键.用去字符键表示DEL和SUPPR.

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

但是由于某些原因,即使事件被消耗,按Delete键仍会删除结尾字符.

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

感谢您的时间!

推荐答案

KEY_TYPED 仅在按下生成 UTF 输出的键之后才会触发事件. KEY_TYPED 事件不会在 BACK_SPACE DELETE 键按下时生成.请使用 KEY_PRESSED 事件.

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

event.consume() 放入if块内将仅取消这些按钮.其他人将照常工作.

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

这对我来说很好.

这篇关于禁用JavaFX TextField中的字符删除键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆