i've tried using recursion, but it's failed as it raise the StackOverflow exception.
should i use something like a sleep function?
is there any other solution, i hope a simple solution (no threading things)
thank you.
Recursion is not the way to go here but you bet you have to use a bit of threading
here: one thing has to keep on rolling the die; another thing has to display a die
value and yet another thing has to be alive to listen to a button press to make the
first thing stop.
Swing is a single thread of execution. This thread listens to events and draws
everything on the screen; if you lock it up in a loop to roll the die it can't do its
tasks anymore and the screen 'freezes'. That is not what you want.
But things aren't that difficult if you design it well. Build a simple class Die that
does this:
-
public class Die {
-
...
-
public Die() { ... }
-
...
-
public roll() {
-
// randomly produce a number 1, 2, ... 6
-
// and show it in the label
-
}
-
}
-
Here is a class Roller that rolls the Die continuously; it sleeps 'ms' milliseconds
between rolls:
-
public class Roller implements Runnable {
-
private long ms;
-
volatile private boolean stop;
-
public Roller(long ms, Die die) {
-
this.ms= ms;
-
this.die= die;
-
}
-
public void stop() { this.stop= true; }
-
public void run() {
-
while (!stop) {
-
die.roll();
-
try {
-
Thread.sleep(ms);
-
}
-
catch (InterruptedException ie) { /* shouldn't happen */ }
-
}
-
}
-
}
-
This object rolls a die, sleeps and repeats the same over and over again until
its 'stop' variable is set to 'true'.
Note that I made this Roller class implement the Runnable interface so it can
be handed to a Thread that can run it when the thread is started. The second
button should be passed this Roller as well so it can stop it when the button
is pressed.
The first button should create a Roller, pass it to the second button and hand
the roller to a freshly created Thread and start the thread.
I'm about sure that you can manage from here.
kind regards,
Jos