问题
So I'm writing a program that plays Reversi/Othello against a player. I wrote a method to make a short animation of the pieces flipping-
public void flip(int row, int col, Graphics window)
{
Color a;
if (pieces[row][col]==1)
a = Color.black;
else
a = Color.white;
for ( int size = 90; size>0; size-=2)
{
try { Thread.sleep(11,1111); } catch (InterruptedException exc){}
window.setColor(new Color( 0, 100, 0 ));
window.fillRect(row*100+3, col*100+3, 94, 94);
window.setColor(a);
window.fillOval(row*100 + 5, col*100+5+(90-size)/2, 90, size);
}
if (a==Color.black)
a=Color.white;
else
a=Color.black;
for ( int size = 0; size<90; size+=2)
{
try { Thread.sleep(11,1111); } catch (InterruptedException exc){}
window.setColor(new Color( 0, 100, 0 ));
window.fillRect(row*100+3, col*100+3, 94, 94);
window.setColor(a);
window.fillOval(row*100 + 5, col*100+5+(90-size)/2, 90, size);
}
}
It works well and looks great, but the problem is that since thread.sleep pauses the entire program, it can only flip one piece at a time. Is there something I can do to pause just that method without interrupting the rest of the program?
Thanks everyone. The new thread worked, but now I have a different problem. The three setcolor methods in the flip method are getting mixed up. I think it's because some threads are setting the color to green, some to black and some to white. How do I fix this?
回答1:
You should run flip
in separate Thread
in that case. The simplest example:
Thread t = new Thread(new Runnable() {
public void run() {
flip();
}
});
t.start();
回答2:
You should make run this method inside a dedicated thread created from your main program.
回答3:
What you are targetting is asynchronous programming: schedule a javax.swing.Timer
that, each time it fires, does one animation step. This would be the idiomatic way for a GUI program; the approach with a separate thread that sleeps in a loop and uses invokeLater
in each step will also work, but is less elegant because it uses more system resources (another thread that mostly just sleeps).
回答4:
You need to create a separate thread that will handle the animation. That thread can call Thread#sleep
, since Thread#sleep
does not pause "the entire program", but only the current thread. At each step in the animation, it should change some state indicating the current stage of the piece flip animation and then request a repaint.
来源:https://stackoverflow.com/questions/14366777/how-do-i-make-method-pause-without-pausing-the-whole-program