【问题标题】:Javafx getSource() from KeyEvent来自 KeyEvent 的 Javafx getSource()
【发布时间】:2015-12-29 03:23:28
【问题描述】:

我正在尝试获取 KeyEvent 的来源(在我的情况下为 TextField)。我可以使用e.getSource().toString() 打印它,它打印字符串TextField[id=molarMass, styleClass=text-input text-field],但我只想得到TextFieldID,所以我也可以将我的方法用于其他TextField,而不仅仅是这个。

代码:

public void correctTextField(KeyEvent e) {
    System.out.println(e.getSource().toString());
    if (e.getCode() != KeyCode.BACK_SPACE && !e.getCode().isArrowKey()) {
        int caretPosition = molarMass.getCaretPosition();
         molarMass.setText(DataUse.testForOnlyNumbers(molarMass.getText()));
        molarMass.positionCaret(caretPosition);
    }
}

correctTextField 由 TextField 每次按下键时使用,我想使用特定的 TextFieldID 而不是在代码中使用 molarMass

【问题讨论】:

    标签: java javafx keyevent


    【解决方案1】:

    您可以将源转换为节点并从那里获取 ID。

    例如:

    Node n = (Node)event.getSource();
    String id = n.getId();
    
    //Do your logic....
    

    或者,如果您确定它只会是那样的话,您可以转换为 TextField....

    【讨论】:

    • 谢谢。这实际上比我想象的要容易得多。最简单的解决方案:TextField origin= ((TextField) e.getSource());
    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多