Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 调用.addActionListener()时使用哪些参数?_Java_Button_This_Actionlistener_Frames - Fatal编程技术网

Java 调用.addActionListener()时使用哪些参数?

Java 调用.addActionListener()时使用哪些参数?,java,button,this,actionlistener,frames,Java,Button,This,Actionlistener,Frames,最近我在Java学习了很多东西,但有些东西真的让我感到困扰。例如,当程序涉及到一个构造函数时,我学会了如何使用ActionListeners public class test extends JFrame implements ActionListener { JButton button; public test { setLayout(null); setSize(1920,1080); setTitle("test"); setDefaultCloseOperation(JFrame

最近我在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
    }
}

它是要处理
ActionEvent
的类的实例

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

addActionListener(InstanceOffmyClass)


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

你可能想考虑不做你的代码> jFrase<代码>实现<代码> ActuistListor < /C> >:这意味着

  • 它是类接口的一部分,它实现了
    actionPerformed
    ;但您可能不希望其他类直接调用它
  • 您只能“一次”实现它,因此必须使用条件逻辑来确定事件的来源,然后适当地处理它
  • 另一种方法是创建一个特定于
    按钮的操作侦听器:

    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

    看看Javadoc什么是该类的实例?我对此感到困惑,对不起。就像我最初期望的那样,它是与.addActionListener(actionPerformed)类似的东西;它可以是实现
    ActionListener