可以使用唯一的事件监听器来识别按下了 whst btn 吗?
我尝试了这段代码,但没有成功
ActionListener one = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gr1.getCounter1() < 5) {
gr1.setCounter1(gr1.getCounter1() + 1);
if (arraybtn[1].isSelected())
test1.setIcon(play1a);
if (arraybtn[2].isSelected())
test1.setIcon(play1b);
if (arraybtn[3].isSelected())
test1.setIcon(play1c);
if (arraybtn[4].isSelected())
test1.setIcon(play1d);
if (arraybtn[5].isSelected())
test1.setIcon(play1e);
} else {
pn5.setText("No more cards");
}
}
};
谢谢!
最佳答案
使用 ActionEvent
对象中的 getSource
方法。
您的代码如下所示:
if (e.getSource() == arraybtn[1])
test1.setIcon(play1a);
if (e.getSource() == arraybtn[2])
test1.setIcon(play1b);
if (e.getSource() == arraybtn[3])
test1.setIcon(play1c);
if (e.getSource() == arraybtn[4])
test1.setIcon(play1d);
if (e.getSource() == arraybtn[5])
test1.setIcon(play1e);
获取事件源(即按下的按钮)。
http://download.oracle.com/javase/1.4.2/docs/api/java/util/EventObject.html#getSource()
关于java - java按下了什么按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4914603/