如何为多个不同的无名 JButton 设置 ActionListener。当他们都有相同的名字或没有名字时,如何独立对待他们?
How to set the ActionListener for multiple different nameless JButtons. How can they be treated independently when they all have the same or no name?
这是一个例子。我有一个由不同按钮组成的网格(将每个按钮添加到网格布局中),我不想为它们中的任何一个命名,但想为它们中的每一个执行不同的命令。重写 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
创建唯一标识符。
在这种情况下,最好在容器中私有实现 ActionListener
接口(JPanel
、JFrame
、...),而不是使用匿名 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
您可以通过计算二维数组中的索引找出按下了哪个按钮.
希望对您有所帮助。
这是一个例子。我有一个由不同按钮组成的网格(将每个按钮添加到网格布局中),我不想为它们中的任何一个命名,但想为它们中的每一个执行不同的命令。重写 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
创建唯一标识符。
在这种情况下,最好在容器中私有实现 ActionListener
接口(JPanel
、JFrame
、...),而不是使用匿名 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
您可以通过计算二维数组中的索引找出按下了哪个按钮.
希望对您有所帮助。