Is there any way to set up a loop to create multiple very similar action-listeners? For purely academic purposes, I created a card game, each card is a button, when you click on the card, it should turn face-up. The game works fine, but each action listener is set up individually. Below is my attempt at a loop.
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
}
}
EDIT: First, I never thought "string1 string2 = new string1();" would work, I was just going for a general idea.
Judging from the comments, it seems I have asked this question in a confusing way, all I meant is I have this in the constructor:
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);
And later this:
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);
}
}
And I wanted to know if it was possible to put all this into a loop. It seems the answer is no, but I was just asking.
string1 string2 = new string1();should do?string1 string2 = new string1()there's a lot to explain here. Try finding some tutorial like: docs.oracle.com/javase/tutorial or learnjavaonline.orgcardis, but most components that support theActionListenerAPI require an instance of anActionListenerwhen registering...