Continue showing dialog when input validation fails

I currently have a dialog with four text fields from which the input is collected. When the input does not meet my requirements, the dialog should remain open and display an error message. I currently have the following code:

dlg.setResultConverter(dialogButton -> { if (dialogButton == createButtonType) { ArrayList<String> returnList = getInput(); if (returnList != null) { return returnList; } else { dlg.showAndWait(); } } return null; }); Optional<ArrayList<String>> result = dlg.showAndWait(); result.ifPresent(customerDetails -> { //Use the input for something }); 

The getInput() method retrieves text from TextFields and checks for certain requirements. When the input passes, four lines are placed in an ArrayList<String> . Otherwise, the method returns null . As you can see, the result converter checks to see if the null method returned. If it is not, it simply returns an ArrayList<String> .

But, when the check fails, the dialog should remain open. It works with dlg.showAndWait() , but the disadvantage is that it causes an error: java.lang.IllegalStateException: Stage already visible . (it continues to work, but getting the error is not the way it should be)

My question is: does anyone know how to do this without causing an error?

Note. I am using JavaFX 8 (JDK 1.8.0_40), which has built-in dialog features.

+5
source share
3 answers

Add listeners to your TextField s by validating user input.

If the user input is valid, enable the "OK" Button (or its name), if the user input is invalid, disable the Button .

If the Button to close Dialog disabled, the only way to close Dialog is to cancel, which will result in an empty Optional .

+5
source
 final Button okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK); okButton.addEventFilter(ActionEvent.ACTION, ae -> { if (!isValid()) { ae.consume(); //not valid } }); 

Works great for me. Just use the filter on first run.

BTW is described in white papers .

+15
source

Suppose the dialog with TextField and the Ok button.

The button is disabled for starters and enabled when you enter valid data in a TextField (text between 5 and 25 characters long). A ChangeListener attached to a TextField StringProperty controls the on / off state of the button.

 TextField textFld = new TextField(); ... ButtonType buttonTypeOk = new ButtonType("Okay", ButtonData.OK_DONE); dialog.getDialogPane().getButtonTypes().add(buttonTypeOk); final Button okButton = (Button) dialog.getDialogPane().lookupButton(buttonTypeOk); okButton.setDisable(true); textFld.textProperty().addListener((observable, oldValue, newValue) -> { okButton.setDisable(newValue.trim().length() < 5 || newValue.trim().length() > 25); }); 
0
source

Source: https://habr.com/ru/post/1209323/


All Articles