我正在构建一个简单的计算器。为了生成所有这些按钮,我创建了一个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()
似乎不是这样。
感谢您的回答!
答案 0 :(得分: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;
}
}