为所有按钮使用一个动作监听器

3

比如说我在我的框架中有10个按钮。 我能够为它们使用一个唯一的动作监听器吗? 我的意思是不为每个按钮定义监听器,而是为所有按钮定义一个监听器。 请给出一个例子。 谢谢。


1
可能可以实现...但是你需要使用一个switch块或一堆if-then-else块来执行适用于按钮的代码。这种解决方案很脆弱,难以维护和阅读。此外,它没有性能优势。没有充分的理由使用这种模式。为每个按钮编写单个方法或单个函数对象是一个更好的想法。唯一可能的例外情况是如果所有按钮都执行相同的代码,但即使是这样,最好也将共享代码实现为私有辅助方法。 - scottb
第一个问题回答是“是”,第二个问题的回答是“去试试,有问题再回来”。 - Richard Sitze
5个回答

4
你可以这样做,但是你需要解除所有调用“一控制器”规则的多路复用,除非你有特殊情况,所有按钮都应该执行相同的操作。
这种解除可能涉及一个开关(或更糟糕的是一堆if/then语句),这个开关将成为维护的头疼问题。请参阅此处可能出现问题的示例

2
// Create your buttons.
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
// ...

// Create the action listener to add to your buttons.
ActionListener actionListener = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Execute whatever should happen on button click.
  }
}

// Add the action listener to your buttons.
button1.addActionListener(actionListener);      
button2.addActionListener(actionListener);
button3.addActionListener(actionListener);
// ...

2
当然可以。
class myActionListener implements ActionListener {
    ...
    public void actionPerformed(ActionEvent e) {
        // your handle button click code
    }
}

在JFrame中。
myActionListener listener = new myActionListener ();
button1.addActionListener(listener );
button2.addActionListener(listener );
button3.addActionListener(listener );

等等


注意:您可以使用 if(e.getSource() == button1)if(e.getActionCommand().equals("Button 1"))(如果按钮被赋予了任何文本,例如 new JButton("Button 1");)来确定哪个按钮被按下。 - Brendan

2

检查 ActionEvent 上的 source,并对比每个按钮进行相等性检查,以确定是哪个按钮引发了 ActionEvent。然后您可以为所有按钮使用单个监听器。

    final JButton button1 = new JButton();
    final JButton button2 = new JButton();
    ActionListener l = new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            if (e.getSource() == button1) {
                // do button1 action
            } else if (e.getSource() == button2) {
                // do button2 action
            }
        }
    };
    button1.addActionListener(l);
    button2.addActionListener(l);

1
你可以这样做,在actionPerformed方法中获取动作命令,对于每个按钮设置动作命令。
ActionListener al_button1 = new ActionListner(){
        @Override
        public void actionPerformed(ActionEvent e){
            String action = e.getActionCommand();
            if (action.equals("button1Command")){
                    //do button 1 command
            } else if (action.equals("button2Command")){
                    //do button 2 command
            }
            //...

        }
 }
 //add listener to the buttons
 button1.addActionListener(al_buttons)
 button2.addActionListener(al_buttons)
 // set actioncommand for buttons
 button1.setActionCommand("button1Command");
 button2.setActionCommand("button2Command");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接