这是一个例子。我有一个由不同按钮组成的网格(将每个按钮添加到网格布局中),我不想为其中任何一个按钮命名,但想为每个按钮执行不同的命令。重写 actionPerformed 时如何区分?
/* MULTIPLE BLANK JBUTTONS WHAT DO????????? */
JButton temp;
for(int i = 0; i < BOARD_WIDTH*BOARD_HEIGHT; i++){
temp = new JButton();
temp.setActionEvent("a" + i);
temp.addActionListener(new ActionListener{
//Anonymous Class????? Is there a better way?
}
});
this.add(temp);
最佳答案
使用 JButton#setActionCommand(String)
为循环中的每个 JButton
创建唯一标识符。
在这种情况下,最好在容器(JPanel
、JFrame
...)中私有(private)实现 ActionListener
接口(interface),而不是使用在循环中有一个匿名 ActionListener
实现。这样就更干净了,另一方面,正如 @MadProgrammer 提到的那样,它也不提供对 actionPerformed
的 public
访问权限。
因此,在 actionPerformed
方法中,您可以使用 ActionEvent#getActionCommand
来找出按下了哪个按钮。例如:
public class GameBoard extends JPanel {
public void init(){
MyButtonActionListener actionListener = new MyButtonActionListener();
/* MULTIPLE BLANK JBUTTONS WHAT DO????????? */
JButton temp;
for(int i = 0; i < BOARD_WIDTH*BOARD_HEIGHT; i++){
temp = new JButton();
//temp.setActionEvent("a" + i);
temp.setActionCommand(""+i); // <- Unique Identifier
temp.addActionListener(actionListener);
this.add(temp);
}
}
private static class MyButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
// Decide what to do for each button:
// ...
}
}
}
如果您创建一个 JButton
的二维数组,并且根据 actionCommand
您可以通过计算索引来找出按下了哪个按钮,则可以增强此功能二维数组。
希望这有帮助。
关于java - 如何为多个不同的无名 JButton 设置 ActionListener。当他们都有相同的名字或没有名字时,如何能够独立对待他们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506421/