0

在我的程序中有几个文本字段..服务员需要在随机文本字段中写入产品数量(文本字段应该只允许数字),我需要知道输入了哪个文本字段并获取数字..它也可能发生输入了几个文本字段..

有任何想法吗 ?提前致谢..

4

1 回答 1

1

此方法让 TextField 完成所有处理(复制/粘贴/撤消安全)。不需要进行扩展类。并允许您决定每次更改后如何处理新文本(将其推送到逻辑,或返回到先前的值,甚至修改它)。

  // fired by every text property change
textField.textProperty().addListener(
  (observable, oldValue, newValue) -> {
    // Your validation rules, anything you like
      // (! note 1 !) make sure that empty string (newValue.equals("")) 
      //   or initial text is always valid
      //   to prevent inifinity loop
    // do whatever you want with newValue

    // If newValue is not valid for your rules
    ((StringProperty)observable).setValue(oldValue);
      // (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
      //   to anything in your code.  TextProperty implementation
      //   of StringProperty in TextFieldControl
      //   will throw RuntimeException in this case on setValue(string) call.
      //   Or catch and handle this exception.

    // If you want to change something in text
      // When it is valid for you with some changes that can be automated.
      // For example change it to upper case
    ((StringProperty)observable).setValue(newValue.toUpperCase());
  }
);

对于您的情况,只需将此逻辑放入其中,并将此侦听器添加到您的所有文本字段中。完美运行。

   if (newValue.equals("")) return; 
   try {
       // ammount entered
     Integer i = Integer.valueOf(newValue); 
       // TextField used
     TextField field = (TextField)((StringProperty)observable).getBean();
     // do what you want with this i and field
   } catch (Exception e) {
     ((StringProperty)observable).setValue(oldValue);
   }
于 2014-10-31T11:44:01.597 回答