按需验证控件是 ControlsFx 的问题跟踪器上的一个问题 (on-demand validation option),该问题跟踪器仍处于打开状态,因此 ControlsFx 尚不支持它。
但是有一种方法可以抑制错误修饰:
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setErrorDecorationEnabled(false);
稍后,当您真正想要验证时(例如在提交按钮上),您需要将其重置为默认值:
validationSupport.setErrorDecorationEnabled(true);
validationSupport.redecorate();
这样,每次更改仍然会验证字段,但在您真正希望显示错误修饰之前不会显示它们。
示例:
在此示例中,我们希望仅在数字字段具有焦点时查看验证错误。
public class Sandbox extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
GridPane pane = new GridPane();
pane.add(new Label("Number field:"), 0 , 0);
TextField numberField = new TextField("");
pane.add(numberField, 1, 0);
TextField textField = new TextField("");
pane.add(new Label("Text field:"), 0, 1);
pane.add(textField, 1, 1);
ValidationSupport vs = new ValidationSupport();
vs.setErrorDecorationEnabled(false); // we don't want errors to bother us for now.
vs.registerValidator(numberField, Validator.createRegexValidator("must be digits only!", "\\d*", Severity.ERROR));
// validate and show errors only if number field has the focus
vs.errorDecorationEnabledProperty().bind(numberField.focusedProperty());
primaryStage.setScene(new Scene(pane));
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(Sandbox.class);
}
}
或者如果您只想在第一次点击提交按钮后查看验证错误:
...
Button button = new Button("Submit");
pane.add(button, 0, 2);
ValidationSupport vs = new ValidationSupport();
vs.setErrorDecorationEnabled(false); // we don't want errors to bother us for now.
vs.registerValidator(numberField, Validator.createRegexValidator("must be digits only!", "\\d*", Severity.ERROR));
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
vs.setErrorDecorationEnabled(true); // validate and show errors now!
}
});
...