假设我有一组按钮
private JButton[] myButtons = new JButton[5];
for (int i=0; i<5; i++)
{
myButtons[i] = new JButton(Integer.toString(i));
myButtons[i].setSize(50, 50);
panel.add(myButtons[i]);
}
如何向这些按钮添加监听器,以便当我单击其中一个按钮时,我知道它在哪个数组位置索引?
你有点不在乎,首先在按钮中添加一个ActionListener
myButtons[i].addActionListener(this); // Or some other ActionListener
在actionPeformed
方法中,您可以使用ActionEvent#getSource
查找它是哪个按钮
@Override
public void actionPerformed(ActionEvent evt) {
for (JButton btn : myButtons) {
if (btn.equals(evt.getSource()) {
// Do what ever you need
break;
}
}
}
您也可以使用JButton
的actionCommand
属性
for (int i=0; i<5; i++)
{
myButtons[i] = new JButton(Integer.toString(i));
myButtons[i].setActionCommand("button " + i);
myButtons[i].addActionListener(this);
panel.add(myButtons[i]);
}
当调用actionPeformed
时,使用ActionEvent#getActionCommand
来确定按下了哪个按钮。
一个更好的想法可能是为每个按钮创建一个专用的ActionListener
。。。
public class ButtonActionHandler implements ActionListener {
private final JButton button;
public ButtonActionHandler(JButton button) {
this.button = button;
}
public void actionPerformed(ActionEvent evt) {
// Do what ever you need to do with the button...
}
}
for (int i=0; i<5; i++)
{
myButtons[i] = new JButton(Integer.toString(i));
myButtons[i].addActionListener(new ButtonActionHandler(myButtons[i]));
panel.add(myButtons[i]);
}
另一个想法是使用Action
API,它允许您定义一个自包含的实体,该实体能够配置按钮并自己处理相关的动作事件。有关的更多详细信息,请参阅如何使用操作
但你可能会使用哪一个,归根结底就是为什么你首先需要识别按钮。
如果使用类实现ActionListener
接口,则可以在循环中添加监听器,如下所示。例如,
class TestGUI extends JPanel implements ActionListener{
public TestGUI(){
for(int i=0; i< 5; i++){
....
myButtons[i].addActionListener(this);
}
}
或者,如果您有单独的Listener类或方法。
myButtons[i].addActionListener(new MyListener());
比在行动执行的方法你可以检查按钮点击,
public void actionPerformed(ActionEvent e){
if("0".equals(e.getActionCommand())){
System.out.println("First button is clicked");
}
... so on
}