How to make Numeric | Decimal TextField in JavaFX Example Tutorial

By | December 9, 2016

JavaFx provides various default layout controllers for taking inputs from the user. One such controller is TextField. The problem with this controller is that it accepts every input provided by the user.

If we need a TextField which accepts floating point numbers or double values, then we need to modify the existing TextField. Textfields with numeric values are needed for making apps/softwares that require numeric calculations.

Numeric TextField:

step-1) Create a normal TextField in JavaFx App.
step-2) Add a listener to the textfield that calls when text is changed in the textfield as shown below.

textField.textProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				if (!newValue.matches("\\d{0,7}([\\.]\\d{0,4})?")) {
					vehiclePrice_TextField.setText(oldValue);
				}
			}
		});

Thats it! :-p

“\\d{0,7}([\\.]\\d{0,4})?” <- Its the regular expression for numeric values that can be accepted. Explanation for the above regular expression: Screen Shot 2016-12-09 at 10.50.41 AM

You can change the regular expression for changing the length of the numeric value to be accepted.
The values that can be accepted by the Numeric Textfield we just created are shown below.
Screen Shot 2016-12-09 at 10.22.47 AM

Thank You!

414 total views, 1 views today

(Visited 152 times, 1 visits today)