如何在JavaFX的文本字段中禁用空格键?

huangapple go评论61阅读模式
英文:

How can I disable the spacebar in a textfield in JavaFX?

问题

我有一个问题。我想完全禁用文本框的空格键,以便我的输入中没有空格。这是否可能?

if (event.getCode() == KeyCode.SPACE) {
    System.out.println("Spacebar key detected!");
    textfieldName.setText(textfieldName.getText().substring(textfieldName.getLength() - 1));
}

这是我找到的内容,但我想完全禁用空格键。有人可以帮我吗?

谢谢回答 如何在JavaFX的文本字段中禁用空格键?

英文:

I got a question. I would like to disable the space bar completely for that textfield so there are no spaces in my input. How is that possible?

if (event.getCode() == KeyCode.SPACE) {
                    System.out.println("Spacebar key detected!");
                    textfieldName.setText(textfieldName.getText().substring(textfieldName.getLength() -1));
                }
            });

This is what I found, but I would like to disable the spacebar completely. Can anyone help me please?

Thanks for answering 如何在JavaFX的文本字段中禁用空格键?

答案1

得分: 1

或许 这个链接 会有帮助

mytextfield.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent event) {
        if (event.getCode() == KeyCode.SPACE) {
            event.consume(); // 取消空格键
        }
    }
});

另一种方法 是像评论中的 @n247s 建议的那样 进行过滤

英文:

Maybe this will help

mytextfield.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler&lt;KeyEvent&gt;() {
        public void handle(KeyEvent event) {          
            if (event.getCode() == KeyCode.SPACE) {
                event.consume(); // to cancel space key               
            }
        }
    });

Another way is to filter it like @n247s suggested in the comments

huangapple
  • 本文由 发表于 2020年9月7日 15:03:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63772793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定