gpt4 book ai didi

java - 哪种方式是正确的?多个 ActionListener 与 1 个 ActionListener

转载 作者:行者123 更新时间:2023-12-01 19:40:22 28 4
gpt4 key购买 nike

哪种方式实现 ActionListener 更正确?性能上有什么重大差异吗?

在类中实现 ActionListener:

public class MainFrame implements ActionListener {

JButton exampleButton1 = new JButton();
JButton exampleButton2 = new JButton();
JButton exampleButton3 = new JButton();

public MainFrame(){
exampleButton1.addActionListener(this);
exampleButton2.addActionListener(this);
exampleButton3.addActionListener(this);
}


@Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();

if(src.equals(exampleButton1)){
//Do something
}else if(src.equals(exampleButton2)){
//Do something
}else if(src.equals(exampleButton3)){
//Do something
}
}
}

与向每个 JButton 添加 ActionListener 相比:

public class MainFrame {

JButton exampleButton1 = new JButton();
JButton exampleButton2 = new JButton();
JButton exampleButton3 = new JButton();

public MainFrame(){
exampleButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Do something
}
});

exampleButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Do something
}
});

exampleButton3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Do something
}
});
}
}

或者甚至可能使用 Lambdas..?

最佳答案

我更愿意使用单独的 Action 作为按钮的监听器。 Action 是一种稍微高级的监听器,可以在任何可以使用 ActionListener 的地方使用。

它提供了额外的功能,例如:

  1. 同一个 Action 可以被多个组件使用,例如 JButton、JMenuItem
  2. 您可以禁用该操作,这将禁用所有使用该操作的组件
  3. 它允许为您的组件分配助记符和加速器

请参阅 How to Use Actions 上的 Swing 教程有关此概念的更多信息和示例。

关于java - 哪种方式是正确的?多个 ActionListener 与 1 个 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com