我为 JavaFX 应用程序制作了一个配置面板。我设法创建了一个动态更改侦听器,如下所示:
public class InputMaskChecker implements ChangeListener<String> {
public static final String NUMERIC = "^[0-9]*$";
public static final String TEXTONLY = "^\\w*$";
public static final String PASSWORD = "^[\\w\\+\\!\\?\\-\\$\\&\\%£]+$";
public static final String DATASOURCE = "^([a-zA-Z]+:){3}@([a-zA-Z0-9]+:)+[a-zA-Z0-9]+$";
public static final String TCPPORT = "^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[2-9]\\d{3}|1[1-9]\\d{2}|10[3-9]\\d|102[4-9])$";
private static final String STYLE = "-fx-effect: dropshadow(gaussian, red, 4, 0.0, 0, 0);";
public final BooleanProperty erroneous = new SimpleBooleanProperty(false);
private final String mask;
private final int max_lenght;
private final TextField control;
public InputMaskChecker(String mask, TextField control) {
this.mask = mask;
this.max_lenght = 0;
this.control = control;
}
public InputMaskChecker(String mask, int max_lenght, TextField control) {
this.mask = mask;
this.max_lenght = max_lenght;
this.control = control;
}
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
erroneous.setValue(!newValue.matches(mask) || ((max_lenght > 0) ? newValue.length() > max_lenght : false) || newValue.length() == 0);
control.setStyle( erroneous.get() ? STYLE : "-fx-effect: null;");
}
}
在我的控制器中使用它,如下所示:
field1.textProperty().addListener(new InputMaskChecker(InputMaskChecker.DATASOURCE, field1));
field2.textProperty().addListener(new InputMaskChecker(InputMaskChecker.TEXTONLY, field2));
field3.textProperty().addListener(new InputMaskChecker(InputMaskChecker.PASSWORD, field3));
field4.textProperty().addListener(new InputMaskChecker(InputMaskChecker.NUMERIC, 1, field4));
它按预期工作,但有一个小故障:我想让主控制器上的 SAVE 按钮对侦听器做出反应,如果字段有错误,它就会被禁用。
现在是我的头脑风暴请求。你有什么建议吗?
使用共享SimpleBooleanProperty
的 AND-ing 侦听器显然不起作用。
(解决方案)更新:private final BooleanBinding binding;
向控制器
添加一个变量。然后:
InputMaskChecker listener1 = new InputMaskChecker(InputMaskChecker.DATASOURCE, field1);
InputMaskChecker listener2 = new InputMaskChecker(InputMaskChecker.DATASOURCE, field2);
InputMaskChecker listener3 = new InputMaskChecker(InputMaskChecker.DATASOURCE, field3);
InputMaskChecker listener4 = new InputMaskChecker(InputMaskChecker.DATASOURCE, field4);
field1.textProperty().addListener(listener1);
field2.textProperty().addListener(listener2);
field3.textProperty().addListener(listener3);
field4.textProperty().addListener(listener4);
binding = new BooleanBinding() {
{
super.bind(listener1.erroneous, listener2.erroneous, listener3.erroneous, listener4.erroneous);
}
@Override
protected boolean computeValue() {
return (listener1.erroneous.get() || listener2.erroneous.get() || listener3.erroneous.get() || listener4.erroneous.get());
}
};
control.getDisableProperty().bind(binding);
完毕 ;)