JavaFX TextField : Automatically transform text to uppercase

泄露秘密 提交于 2019-12-03 07:27:36

There are a few ways to achieve this:

Override replaceText()

TextField textField = new TextField() {
    @Override public void replaceText(int start, int end, String text) {
        super.replaceText(start, end, text.toUpperCase());
    }
};

Use TextFormatter

textField.setTextFormatter(new TextFormatter<>((change) -> {
    change.setText(change.getText().toUpperCase());
    return change;
}));

This part of the answer triggers textProperty twice and shouldn't be used. It is only here to show the original post.

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

Starting with JavaFX 8u40, you can set a TextFormatter object on a text field. This allows you to apply a filter/converter on the user input. Here's an example.

Listening to changes in the text property comes with the drawback of triggering two change events, one for the initial input (in your case the lower-case characters) and another one for the corrected input (the upper-case characters). If there are are other listeners on the text property, they will need to deal with both events and decide which event is relevant for them. The TextFormatter approach does not have this drawback.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!