有什么方法可以设置循环来创建多个非常相似的 Action 监听器? 纯粹出于学术目的,我创建了一个纸牌游戏,每张纸牌都是一个按钮,当你点击纸牌时,它应该正面朝上。游戏运行良好,但每个 Action 监听器都是单独设置的。下面是我的循环尝试。
String string1;
String string2;
// called by the constructor
public void setupActionListener() {
int loopVar = 0;
while (loopVar <= 16) {
string1 = "card"+loopVar;
string2 = "c"+loopVar;
string1 string2 = new string1(); //A
// -> card0 c0 = new card0();
card[loopVar].addActionListener(string2); //B
// -> card[0].addActionListener(c0);
loopVar = loopVar + 1;
}
// the action listener
public class card0 implements ActionListener { //C
public void actionPerformed(ActionEvent c0) { //D
// perform actions
}
}
编辑: 首先,我从来没有想过“string1 string2 = new string1();”会起作用,我只是想了解一个总体想法。
从评论来看,我似乎以一种令人困惑的方式问了这个问题,我的意思是我在构造函数中有这个:
card0 c0 = new card0();
card[0].addActionListener(c0);
card1 c1 = new card1();
card[1].addActionListener(c1);
card2 c2 = new card2();
card[2].addActionListener(c2);
card3 c3 = new card3();
card[3].addActionListener(c3);
card4 c4 = new card4();
...
card15 c15 = new card15();
card[15].addActionListener(c15);
然后是这个:
public class card0 implements ActionListener {
public void actionPerformed(ActionEvent c0) {
move(0);
}
}
public class card1 implements ActionListener {
public void actionPerformed(ActionEvent c1) {
move(1);
}
}
public class card15 implements ActionListener {
public void actionPerformed(ActionEvent c2) {
move(2);
}
}
...
public class card15 implements ActionListener {
public void actionPerformed(ActionEvent c15) {
move(15);
}
}
我想知道是否可以将所有这些放入一个循环中。看来答案是否定的,但我只是问一下。
最佳答案
您提供的代码不是很丰富,所以我不确定我是否正确理解您,但也许这个伪代码会对您有所帮助。
public class Card extends SomeComponent{
public void turn() {
//doStuff
}
}
public class CardGame {
private SomeComponent[] cards;
public void prepareGame() {
CardListener listener = new CardListener();
for (int i=0; i<=16; i++) {
cards[i] = new Card();
cards[i].addActionListener(listener);
}
}
}
public class CardListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
((Card) e.getSource()).turn();
}
}
您可以使用添加 MouseListener 或 KeyListener 而不是 ActionListener,这不会为您提供有关所发生情况的太多信息。
关于Java - 循环创建 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25394296/