Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform input checks in TextInputDialog in JavaFX?

I have the code below. It describes a simple TextInputDialog (which contains a text field and OK button). How can I perform input checks? (e.g verify that the input is numeric/not-empty and so and so). In the bottom line, I want that the OK button will be disabled if the input is wrong, or if I press OK then nothing will happen if the input is wrong.

TextInputDialog tid = new TextInputDialog("250");
tid.setTitle("Text Input Dialog");
tid.setHeaderText("Input check example");
tid.setContentText("Please enter a number below 100:");
Optional<String> result = tid.showAndWait();
result.ifPresent(name -> System.out.println("Your name: " + name));

In the "ifPresent" section, I can check the input but it will be after the dialog will be closed. How can I fix it?

Here is the dialog

like image 889
HadarShab Avatar asked Aug 31 '25 02:08

HadarShab


1 Answers

You can use getEditor() on the TextInputDialog to get the underlying TextField and lookupButton(ButtonType) on the DialogPane of the dialog to get the OK-Button. Then you can use a binding to implement your desired behavior:

Button okButton = (Button) tid.getDialogPane().lookupButton(ButtonType.OK);
TextField inputField = tid.getEditor();
BooleanBinding isInvalid = Bindings.createBooleanBinding(() -> isInvalid(inputField.getText()), inputField.textProperty());
okButton.disableProperty().bind(isInvalid);

Now you can create a method isInvalid() that validates your input and either returns true (if the button should be disabled), or false (if it should be enabled).

Of course, you can turn this logic around and create a isValid method instead by using the not() method on the binding.

like image 182
Lukas Körfer Avatar answered Sep 02 '25 16:09

Lukas Körfer