JavaFX TextField:自动将文本转换为大写 [英] JavaFX TextField : Automatically transform text to uppercase
问题描述
我的FXMl上有一个JavaFX TextField控件,看起来像这样......
I have a JavaFX TextField control on my FXMl that looks like this...
<TextField fx:id="input_search" onKeyPressed="#keyListener" prefHeight="25.0" prefWidth="197.0" />
我想自动将所有字符更改为用户输入时的大写 。
I want to automatically change all characters to uppercase when the user is typing.
我的控制器中的代码:
public void keyListener(KeyEvent event){
//maybe transform the pressed key to uppercase here...
}
推荐答案
有几种方法可以达到这个目的:
There are a few ways to achieve this:
覆盖 replaceText()
TextField textField = new TextField() {
@Override public void replaceText(int start, int end, String text) {
super.replaceText(start, end, text.toUpperCase());
}
};
使用 TextFormatter
textField.setTextFormatter(new TextFormatter<>((change) -> {
change.setText(change.getText().toUpperCase());
return change;
}));
这部分答案触发 textProperty
两次,不应该。它只是在这里显示原始帖子。
This part of the answer triggers textProperty
twice and shouldn't be used. It is only here to show the original post.
而不是在TextField上使用 onKeyPressed
,使用TextField的 textProperty()
。只需在控制器的 initialize()
中添加以下代码。
Instead of using the onKeyPressed
on your TextField, use the textProperty()
of your TextField. Just add the following code inside the initialize()
of the controller.
input_search.textProperty().addListener((ov, oldValue, newValue) -> {
input_search.setText(newValue.toUpperCase());
});
这篇关于JavaFX TextField:自动将文本转换为大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!