I am currently trying to program a memory/matching game. I am having a problem with trying to figure out how to disable the button after the user has found matching cards. I understand that I need to store the value of the first click and compare it to the second click but still unsure about how it is not working... If anyone could help it would be very appreciated. Thanks.
Consider this code, i have recreated a more simple version of the game which you can actually run below:
main:
public static void main(String[] args) {
start start = new start();
start.main();
}
}
Class for the frame:
class start {
JToggleButton DisplayCards[][] = new JToggleButton[4][4];
Shuffle shuffle = new Shuffle();
void main() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
int y = 20;
int x = 60;
for (int i = 0; i < DisplayCards.length; ++i) {
for (int j = 0; j < DisplayCards[i].length; ++j) {
DisplayCards[i][j] = new JToggleButton("Click Me!");
DisplayCards[i][j].setBounds(x, y, 90, 126);
y = y + 135;
if (y >= 540) {
y = 20;
x = x + 120;
}
frame.add(DisplayCards[i][j]);
DisplayCards[i][j].addActionListener(new Clicked(i, j, shuffle));
}
}
frame.setLayout(null);
frame.setVisible(true);
}
}
Class that shuffles array:
class Shuffle {
String[][] cards = {
{"A", "B", "C", "D"},
{"E", "F", "G", "H"},
{"A", "B", "C", "D"},
{"E", "F", "G", "H"}
};
public void random() {
for (int i = 0; i < cards.length; i++) {
for (int j = 0; j < cards[i].length; j++) {
int i1 = (int) (Math.random() * cards.length);
int j1 = (int) (Math.random() * cards[i].length);
String temp = cards[i][j];
cards[i][j] = cards[i1][j1];
cards[i1][j1] = temp;
}
}
}
}
Class for the ActionListener:
class Clicked implements ActionListener {
String first;
start matching = new start();
boolean state = false;
Shuffle shuffle;
JToggleButton tBtn;
private int i;
private int j;
int posI;
int posJ;
public Clicked(int i, int j, Shuffle shuffle) {
this.i = i;
this.j = j;
this.shuffle = shuffle;
}
public void actionPerformed(ActionEvent e) {
tBtn = (JToggleButton) e.getSource();
if (tBtn.isSelected()) {
tBtn.setText(shuffle.cards[i][j]);
if (!state) {
first = shuffle.cards[i][j];
posI = i;
posJ = j;
System.out.println(first);
state = true;
} else {
if (first.equals(shuffle.cards[i][j])) {
tBtn.setEnabled(false);
System.out.println("Correct!");
} else if (!first.equals(shuffle.cards[i][j])) {
System.out.println("Not it");
tBtn.setText("Click Me!");
matching.DisplayCards[posI][posJ].setText("Click Me!");
first = null;
posI = 0;
posJ = 0;
state = false;
}
}
} else {
tBtn.setText("Click Me!");
}
}
}