ActionListener - 将操作添加到 JButton 的 ArrayList 中

3

我正在构建一个简单的计算器。为了生成所有这些按钮,我已经创建了一个ArrayList,并在循环中初始化了数字,而对于其他的则进行了手动初始化:

        //Button Initialization
        for(int i=0; i<10; i++) {
            numberButtons.add(new JButton(""+i));   //indexes 0-9 of the ArrayList
        }

        numberButtons.add(new JButton(","));        //index 10 and so on
        numberButtons.add(new JButton("C"));
        numberButtons.add(new JButton("+"));
        numberButtons.add(new JButton("-"));
        numberButtons.add(new JButton("\u221A"));
        numberButtons.add(new JButton("*"));
        numberButtons.add(new JButton("/"));
        numberButtons.add(new JButton("="));

我已经为他们添加了 ActionListener:
        //Adding ActionListener
        EventHandling handler = new EventHandling(numberButtons);

        for (JButton buttons : numberButtons) {

            buttons.addActionListener(handler);
        }

在另一个名为 EventHandling 的类中,我想根据按下的数字来启动操作。我创建了以下内容:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;

public class EventHandling implements ActionListener {

     private ArrayList<JButton> numberButtons;

     public EventHandling(ArrayList<JButton> numberButtons) {

        this.numberButtons = numberButtons;
    }

    public void actionPerformed(ActionEvent event) {


        if (event.getSource() == numberButtons.get(1)) {
            System.out.println("Button 1 works!");
        }

        if (event.getSource() == numberButtons.get(2)) {
            System.out.println("Button 2 works!");
        }

     }

}

它能正常工作,但是我想知道是否有更好的方法来处理每个按钮事件,而不是使用if语句。我尝试过使用switch语句,但它不能与对象一起使用,而这些按钮的getText()似乎也不是解决办法。

谢谢您的答复!


2
在那个类似的问题中有一个不错的社区维基答案: http://stackoverflow.com/a/31329139/476791 它展示了如何以通用方式创建按钮。 - slartidan
2个回答

2
您可以使用 event.getActionCommand()。它会返回事件源分配的字符串,而在本例中该源是一个 JButton。
public void actionPerformed(ActionEvent event) {


     switch (e.getActionCommand())
    {
        case "1":System.out.println("pressed button 1");
            break;
        case "2":System.out.println("pressed button 2");
                break;
        case "*":System.out.println("pressed button *");
            break;
        case "\u221A":System.out.println("pressed button \\u221A");
            break;

    }

 }

谢谢您的回复。一开始我读了您的帖子并开始在网上搜索getActionCommand(),但是由于我正在移动中阅读,所以有些复杂。但是一旦我回到家运行了您的代码并理解了它 - 与通过indexOf获取其数字相比,最好使用ifswitch获取对象的字符串。非常感谢! - Dandry

1
另一种可能性:
public void actionPerformed(ActionEvent event) {
   int indx = numberButtons.indexOf( event.getSource() );
   if ( indx >= 0 ) {
      // indx is the index of the button that was pushed
   }
}

谢谢你,不过@Ninth-tail发布了一个更合适的解决方案。但还是谢谢你——我学到了新东西! - Dandry

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