JavaFX TextField: automatically convert text to uppercase

I have a TextField JavaFX 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 types.

Code in my controller:

 public void keyListener(KeyEvent event){ //maybe transform the pressed key to uppercase here... } 
+5
source share
2 answers

Instead of using onKeyPressed on your text field, use textProperty() your TextField. Just add the following code inside the initialize() controller.

 input_search.textProperty().addListener((ov, oldValue, newValue) -> { input_search.setText(newValue.toUpperCase()); }); 
+9
source

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

Listening to changes in a text property occurs with the lack of triggering two change events: one for initial input (lower case characters in your case) and another for corrected input (upper case characters). If there are other listeners in the text property, they will need to figure out both events and decide which event matters to them. The TextFormatter approach does not have this drawback.

+5
source

All Articles