【问题标题】:Javafx how to know which textfield clicked?Javafx如何知道点击了哪个文本字段?
【发布时间】:2013-11-05 05:57:54
【问题描述】:

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

有什么想法吗?提前谢谢..

【问题讨论】:

    标签: javafx textfield


    【解决方案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);
       }
    

    【讨论】:

      猜你喜欢
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多