简体   繁体   English

ActionListener JTextField Java

[英]ActionListener JTextField Java

Suppose we have two JButton objects with captures "Calculate" and "Exit". 假设我们有两个带有“Calculate”和“Exit”捕获的JButton对象。 For the sake of not creating classes implemented by ActionListener, we hve the whole class inplemented by ActionListener, and the method ActionPerformed looks like this: 为了不创建由ActionListener实现的类,我们使用ActionListener来处理整个类,ActionPerformed方法如下所示:

public void actionPerformed(ActionEvent e) {

    if (e.getActionCommand().equals("Calculate"))
        // do what "calculate" button does
    else if (e.getActionCommand().equals("Exit"))
        System.exit(0);

}

My question is what if we have two text fields (JTextField). 我的问题是如果我们有两个文本字段(JTextField)。 How should we rewrite actionPerformed method? 我们应该如何重写actionPerformed方法? what is the method to return the JTextField name after the user hits Enter key in that field? 在用户点击该字段中的Enter键后返回JTextField名称的方法是什么?

For the sake of not creating classes implemented by ActionListener... 为了不创建ActionListener实现的类...

You should not be using a single listener. 您不应该使用单个侦听器。 Instead you should be using a separate listener for each function you want to implement. 相反,您应该为要实现的每个函数使用单独的侦听器。

My question is what if we have two text fields (JTextField). 我的问题是如果我们有两个文本字段(JTextField)。

Instead of adding an ActionListener to the text field you can add a customized TextAction . 您可以添加自定义TextAction而不是将ActionListener添加到文本字段。 The TextAction supports a getFocusedComponent() method which will return the text field that currently has focus. TextAction支持getFocusedComponent()方法,该方法将返回当前具有焦点的文本字段。 This is how all Swing Actions are implement on text components. 这就是所有Swing Actions在文本组件上的实现方式。

For a simple example you can check out: What text input component last had the focus? 有一个简单的例子,你可以看看: 最后一个文本输入组件有焦点?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM