S
stinkinrich88
Hello. I have the following class:
import javax.swing.*;
import java.awt.event.*;
class Die extends JLabel implements ActionListener
{
private int counter;
private Timer dieTm = new Timer(70, this);
private int dieValue;
private ImageIcon[] dieImg = new ImageIcon[6];
public Die()
{
ClassLoader cldr = this.getClass().getClassLoader();
for(int i = 1; i<7; i++)
dieImg[i-1] = new ImageIcon(cldr.getResource(i +".gif"));
}
public int doRoll()
{
setVisible(true);
counter = 0;
dieTm.start();
while(dieTm.isRunning());
dieValue = (int)Math.ceil((Math.random()*6));
setIcon(dieImg[dieValue-1]);
return dieValue;
}
public void actionPerformed(ActionEvent e)
{
setIcon(dieImg[(int)Math.ceil((Math.random()*6))-1]);
counter++;
System.out.println(counter);
if (counter == 10) dieTm.stop();
}
}
That should animate a dice rolling and stop at a value. It works fine
when I call it within the code, but when I call it from an action
Listener the timer's action listener doesn't run, but the timer
isRunning returns true so it ends up in an infinite While loop waiting
for it to finish.
Any ideas? Thanks!
import javax.swing.*;
import java.awt.event.*;
class Die extends JLabel implements ActionListener
{
private int counter;
private Timer dieTm = new Timer(70, this);
private int dieValue;
private ImageIcon[] dieImg = new ImageIcon[6];
public Die()
{
ClassLoader cldr = this.getClass().getClassLoader();
for(int i = 1; i<7; i++)
dieImg[i-1] = new ImageIcon(cldr.getResource(i +".gif"));
}
public int doRoll()
{
setVisible(true);
counter = 0;
dieTm.start();
while(dieTm.isRunning());
dieValue = (int)Math.ceil((Math.random()*6));
setIcon(dieImg[dieValue-1]);
return dieValue;
}
public void actionPerformed(ActionEvent e)
{
setIcon(dieImg[(int)Math.ceil((Math.random()*6))-1]);
counter++;
System.out.println(counter);
if (counter == 10) dieTm.stop();
}
}
That should animate a dice rolling and stop at a value. It works fine
when I call it within the code, but when I call it from an action
Listener the timer's action listener doesn't run, but the timer
isRunning returns true so it ends up in an infinite While loop waiting
for it to finish.
Any ideas? Thanks!