【问题标题】:JavaFX TextField ValidationJavaFX 文本字段验证
【发布时间】:2016-08-19 16:07:57
【问题描述】:

我想验证 JavaFX TextField 中输入的数据是否为整数。我只想在用户完全写入输入并移至下一个字段后进行此验证。

尝试了一种方法,但它不起作用,我不明白为什么:

product_quantity.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
       if (!product_quantity.isFocused()) {
          if (!product_quantity.getText().matches("[0-9]*")) {
              total_cost.setStyle("-fx-background-color: red;");
          } else {
              total_cost.setText(Float.toString(Float.parseFloat(newValue) * Float.parseFloat(unit_cost.getText())));
              total_cost.setStyle("-fx-background-color: white;");
          }
       }
    }
});

如何做到这一点?

【问题讨论】:

  • 您是否有理由不只是设置 TextField 的 TextFormatter?例如:textField.setTextFormatter(new TextFormatter(new NumberStringConverter(NumberFormat.getIntegerInstance())));
  • 如果输入无效,我必须将 total_cost 字段框变为红色。当输入正确完成后,我会移除颜色。
  • 一个小问题,每当我将颜色更改为红色,然后是白色时,字段框看起来不像以前那样原始。我怎样才能把它恢复到原来的形式。我用这个:total_cost.setStyle("-fx-background-color: red;");
  • total_cost.setStyle(null); 修复了样式以恢复默认值。

标签: java javafx


【解决方案1】:

您可以向focusProperty() 添加侦听器,而不是向textProperty() 添加侦听器。这样,只有在 TextField 失去或获得焦点时才会触发侦听器。

textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
    if(!newValue) { // we only care about loosing focus
       // check condition and apply necessay style
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多