验证控件中的可观察值

时间:2019-04-02 16:32:05

标签: javafx controlsfx

我有以下代码

  public ValidationResult notNull(Control control, String content) {
        boolean condition = content.length() <=0;
        return ValidationResult.fromMessageIf(control, "Field is empty!", Severity.WARNING, condition);
    }

它检查文本字段中是否有任何字符,

我这样称呼

validator = new ValidationSupport();

validator.registerValidator(itemIdTf,vals::notNull);

最后就是这样做

validator.invalidProperty().addListener((observable, oldValue, newValue) -> {
            itemIdTf.pseudoClassStateChanged(PseudoClass.getPseudoClass("negative"), oldValue);});

这有效,它为某些控件设置了伪类,但是当我在同一个验证器上只有很少的文本字段控件时,它必须等待所有它们都被验证,然后才能更改伪类。

所以我想也许可以在ValidationResult方法中做到这一点,因为我认为使用很多验证器可能不好。我怎么不知道这是否可行,我需要每个控件都唯一的监听器,而不是验证结果。

1 个答案:

答案 0 :(得分:0)

好吧,我发现了一些可行的方法,但是仍然存在一些未解决的问题:

  public ValidationResult notNull(Control control, String content) {



        boolean condition = content.length() <=0;

      control.pseudoClassStateChanged(positive,!condition);

        return ValidationResult.fromMessageIf(control, "Field is empty!", Severity.ERROR, condition);
    }

我正在使用css样式验证器,因此来自此行的内容不起作用(至少不是全部)

return ValidationResult.fromMessageIf(control, "Field is empty!", Severity.ERROR, bp.getValue());

在这里上面有字符串“ Field is empty”,它应该是控制的工具提示,但是它从未设置,因此我只是在验证内创建了自己的工具提示,并将其添加到控件中。

然后整个事情看起来像这样:

PseudoClass positive = PseudoClass.getPseudoClass("positive");
    final Tooltip notNullTooltip = new Tooltip("Must have some value");
      public ValidationResult notNull(Control control, String content) {

            boolean condition = content.length() <=0;

          control.pseudoClassStateChanged(positive,!condition);
          control.setTooltip(notNullTooltip);
            return ValidationResult.fromMessageIf(control, "Field is empty!", Severity.ERROR, condition);
        }

它确实有效,如果有人有更优雅的解决方案,我将非常感激。