如何在 JavaFX 的 TextInputDialog 中执行输入检查?

Had*_*hab 3 java dialog javafx javafx-2 javafx-8

我有下面的代码。它描述了一个简单的TextInputDialog(其中包含一个文本字段和 OK 按钮)。如何执行输入检查?(例如验证输入是数字/非空等等)。归根结底,如果输入错误我希望 OK 按钮将被禁用,或者如果我按 OK,那么如果输入错误,则不会发生任何事情。

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));
Run Code Online (Sandbox Code Playgroud)

在“ifPresent”部分,我可以检查输入,但它将在对话框关闭之后进行。我该如何解决?

这是对话框

Luk*_*fer 5

您可以使用getEditor()onTextInputDialog来获取底层,TextFieldlookupButton(ButtonType)DialogPane对话框中使用 来获取 OK- Button。然后您可以使用绑定来实现您想要的行为:

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);
Run Code Online (Sandbox Code Playgroud)

现在您可以创建一个方法isInvalid()来验证您的输入并返回true(如果按钮应该被禁用),或者false(如果它应该被启用)。

当然,您可以扭转这个逻辑并isValid通过使用not()绑定上的方法来创建一个方法。