ActionEvent 如何工作以及如何创建其对象以在按下按钮时执行任务?

How ActionEvent work and how its object is created down to do carry out the task when a button is pressed?

任何人都可以让我理解这个逻辑的流程,当按下按钮 b1 时会发生一些动作(执行一些语句),但是为什么我们给出如下语法,ActionEvent object ae 已创建,它是如何工作的? 如果我不使用 Inner class 那么我还有其他表示吗?

JButton b1=new JButton();
b1.addActionListener((ActionEvent ae) -> {
    //Statements;
});

您可以像这样添加动作事件。

JButton b1 = new JButton();
b1.addActionListener(this);

那么你必须做这个class

public void actionPerfomed(ActionEvent ae){
   if(ae.getSource()==b1){
      //your commands here
     }
}

注意:确保实施ActionListener

所有 ActionListener 实现功能:

public void actionPerformed(ActionEvent e) { 
    ...//code that reacts to the action... 
}

此代码创建一个新的匿名 class,它实现 ActionListener 并将 actionPerformed 函数覆盖为您想要的任何内容。具有此功能的新对象已添加到 foo 的 ActionListeners 内部列表中:

foo.addActionListener( new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
        ...//code that reacts to the action...
    }
});

A shorthand 是使用 lambda 表达式,因为 ActionListener 只有一个函数要覆盖,所以编译器知道你指的是哪一个(有关更多信息,请参阅有关 lambda 的文档):

foo.addActionListener( 
    (e) -> { 
        ...\code that reacts to the action...
    } 
);

当一个动作发生时,foo 将通过它列出的 ActionListener 对象,并在每个对象上调用 actionPerformed()。每个对象的函数版本代码依次为运行。

顺便说一句,最好不要在 actionPerformed() 中做太多工作,因为它是在 Swing 线程中执行的,此处性能低下意味着用户界面无响应。如果您需要 运行 一个耗时的动作来响应一个动作,请考虑在此函数内启动一个新线程,或者简单地设置一个标志以供现有线程检测。