Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX TextField : Automatically transform text to uppercase

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.

The code in my controller :

public void keyListener(KeyEvent event){
    //maybe transform the pressed key to uppercase here...
}
like image 422
Martin Avatar asked Jun 17 '15 07:06

Martin


1 Answers

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());
});
like image 177
ItachiUchiha Avatar answered Oct 21 '22 12:10

ItachiUchiha