How do I make method pause without pausing the who

2019-07-21 09:35发布

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?

4条回答
仙女界的扛把子
2楼-- · 2019-07-21 10:12

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-21 10:14

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();
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-21 10:18

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).

查看更多
孤傲高冷的网名
5楼-- · 2019-07-21 10:20

You should make run this method inside a dedicated thread created from your main program.

查看更多
登录 后发表回答