Images not showing up until end of for loop

R

Ryan Lucas

Guest
I was programming a slot machine in java with Windowbuilder, and I wanted to add an animation so that it looked like it was actually spinning. So, I made a for loop that counted 15 times, and a Thread.sleep(15) function. The loop works, but it doesn't display the images until the loop is done.

I've tried TimeUnit.MICROSECONDS.sleep(100);, and Thread.sleep(5000);. None of those produce the expected output. I’ve also tried wait(), but that gives an exception:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException


JButton btnRoll = new JButton("Roll!!!!");
btnRoll.setFont(new Font("Tahoma", Font.PLAIN, 25));
btnRoll.setBounds(384, 360, 174, 170);
getContentPane().add(btnRoll);
btnRoll.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int credits = creditsNum[0];
isZero[0] = credits <= 0;
int a = 0;
int b = 0;
int c = 0;
try {
for (int i = 0; i <= 15; i++) {
a = slot.roll();
System.out.println(a);
b = slot.roll();
System.out.println(b);
c = slot.roll();
System.out.println(c);
img1.setIcon(new ImageIcon(GUI.class.getResource(img[a])));
img2.setIcon(new ImageIcon(GUI.class.getResource(img)));
img3.setIcon(new ImageIcon(GUI.class.getResource(img[c])));
Thread.sleep(15);
}
} catch (InterruptedException e1) {}
System.out.println("hello");
a = slot.roll();
System.out.println(a);
b = slot.roll();
System.out.println(b);
c = slot.roll();
System.out.println(c);
img1.setIcon(new ImageIcon(GUI.class.getResource(img[a])));
img2.setIcon(new ImageIcon(GUI.class.getResource(img)));
img3.setIcon(new ImageIcon(GUI.class.getResource(img[c])));
credits = Integer.parseInt(slot.credits(a,b,c,credits));
if (isZero[0] == true) {
JOptionPane.showMessageDialog(null, message[rand.nextInt(5)]);
System.exit(0);
}
else {
lblHighScore.setText("Credits: " + credits);
creditsNum[0] = credits;
}
}
});


I expected it to spin like a real slot machine, but it just waits 1500 milliseconds then it shows the updated image.

Continue reading...
 
Top