Posted By:
D_Bratton
Posted On:
Wednesday, January 19, 2005 09:52 AM
Hello, I'm attempting to get a basic animation going in a Frame with the ability to pause the thread using the space bar. Attempting to be a good, compliant Java programmer, I'm using Sun's advice on how to accomplish this with wait() and notify() , rather than the oh-so-evil suspend() and resume() . Here's the necessary bits of code: Class Animation extends Frame implements Runnable { private volatile Thread animThread; private volatile boolean animThreadSuspended; Animation() { addMouseListener( new MouseAdapter() { public synchronized void mousePressed(MouseEvent e)
More>>
Hello,
I'm attempting to get a basic animation going in a Frame with the ability to pause the thread using the space bar. Attempting to be a good, compliant Java programmer, I'm using Sun's advice on how to accomplish this with
wait()
and
notify()
, rather than the oh-so-evil
suspend()
and
resume()
.
Here's the necessary bits of code:
Class Animation extends Frame implements Runnable
{
private volatile Thread animThread;
private volatile boolean animThreadSuspended;
Animation()
{
addMouseListener(
new MouseAdapter()
{
public synchronized void mousePressed(MouseEvent e)
{
e.consume();
animThreadSuspended = !animThreadSuspended;
if(!animThreadSuspended)
{
notify();
}
}
});
animThread = new Thread(this);
animThread.start();
}
public void run()
{
while(true)
{
try
{
synchronized(this)
{
if(animThreadsSuspended)
{
wait();
}
}
}
catch(InterruptedException ie){}
repaint();
}
}
}
There is, of course, a lot more to it, but these are the parts giving me trouble. As near as I can tell,
notify()
in the MouseListener is not being called on the same object that
wait()
is waiting on in the
run()
method. Because of this, the animation pauses when I click the mouse since
animThreadSuspended
is set to true, but the animation thread doesn't resume upon another click, despite
animThreadSuspended
getting reset to false.
I'm sure there's a very simple way to remedy this that I'm overlooking - any help would be most appreciated.
Dan
<<Less