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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With