I am creating a number puzzle game in 3 by 3 grid layout panel. First i random 8 numbers and push them to a stack and then pop their value and set them as button text. The application runs fine but sometimes i have this error printed out: Exception in thread "AWT-EventQueue-0" java.util.EmptyStackException at java.util.Stack.peek(Stack.java:102) at java.util.Stack.pop(Stack.java:84)
and it points to this line of code: buttons[i].setText(randomStack.pop() + "");
I know that it is something with the multi-threading but i can not figure out, please help me.
public Frame() {
JPanel panel = new JPanel();
Stack<Integer> randomStack = new Stack();
while(randomStack.size() < 8) {
int n = new Random().nextInt(8) + 1;
if(!randomStack.contains(n)) {
randomStack.push(n);
}
}
panel.setLayout(new GridLayout(3, 3));
panel.setPreferredSize(new Dimension(200 ,200));
buttons = new JButton[9];
for(int i = 0; i < 9; i++) {
buttons[i] = new JButton();
buttons[i].setSize(30, 30);
panel.add(buttons[i]);
}
Random random = new Random();
int n = random.nextInt(10);
for(int i = 0; i < 9; i++) {
if(i != n) {
buttons[i].setText(randomStack.pop() + "");
}
}
add(panel, BorderLayout.NORTH);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
}