【问题标题】:What parameters are used when .addActionListener() is called?调用 .addActionListener() 时使用了哪些参数?
【发布时间】:2016-05-26 08:15:43
【问题描述】:

我最近在 Java 方面学到了很多东西,但有些东西确实困扰着我。例如,当程序涉及构造函数时,我学习/被教导如何使用 ActionListeners,

public class test extends JFrame implements ActionListener {
JButton button;

public test 
{
setLayout(null);
setSize(1920,1080);
setTitle("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("");
button.setBounds(x,x,x,x);
button.AddActionListener(this); //What can replace the this parameter here.
button.setVisible(true);
add(button);
}
public static void main(String[] args) {
    test testprogram = new test();
    test.setVisible(true);
}
@Override
    public void actionPerformed(ActionEvent clickevent) {
    if (clickevent.GetSource() == button) { 
      //DoSomething
    }
}

【问题讨论】:

  • 看看javadoc

标签: java button this actionlistener frames


【解决方案1】:

它可以是任何实现ActionListener的东西。

您可能要考虑不让您的 JFrame 实现 ActionListener:这意味着

  1. 它是类接口的一部分,它实现actionPerformed;但您可能不希望其他类直接调用它。
  2. 您只能实现“一次”,因此您最终必须有条件逻辑来确定事件的来源,然后适当地处理它。

另一种方法是创建一个button-specific action listener:

button.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent clickevent) {
    // Don't need to check if it is from button, nothing else
    // could have created the event.
  }
});

并从test 类中删除implements ActionListener

【讨论】:

    【解决方案2】:

    这是要处理ActionEvent的类的实例。

    来自Documents

    将事件处理程序类的一个实例注册为一个监听器 或更多组件。例如:

    someComponent.addActionListener(instanceOfMyClass);

    【讨论】:

    • 什么会被视为类的实例?我对这个抱歉感到困惑。就像我最初预期的那样,它类似于 .addActionListener(actionPerformed);
    • 可以是任何实现ActionListener的类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多