Javafx如何知道哪个文本域点击了?

时间:2013-10-26 00:11:08

标签: javafx textfield

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

任何想法?提前谢谢..

1 个答案:

答案 0 :(得分: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);
   }