在一个循环中重绘 [英] repaint in a loop

查看:103
本文介绍了在一个循环中重绘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java Swing编写游戏。我希望每次循环执行时都会绘制一个小延迟,以在屏幕上创建级联效果。我相信系统中的效率例程会将对 repaint()的调用折叠为单个调用。无论如何,在总延迟之后,所有变化都会立即发生。有没有办法强制系统立即重新绘制,然后延迟循环的每次迭代?

I am writing a game using Java Swing. I want to paint each time a loop executes with a small delay in between to create a cascade effect on screen. I believe that the efficiency routines in the system are collapsing the calls to repaint() into a single call. At any rate, the changes all occur at once after the total delay. Is there some way to force the system to repaint immediately and then delay on each iteration of the loop?

我的代码:

for(int i=0;i<10;i++){
    JButton[i].setBackground(Color.WHITE);
    JButton[i].repaint();
    Thread.sleep(2000);
    JButton[i].setBackground(Color.GRAY);
    JButton[i].repaint();
}


推荐答案

您可以使用 JComponent.paintImmediately 强制立即重绘。

You can use JComponent.paintImmediately to force an immediate repaint.

编辑:再次阅读你的问题后,我发现你可能正在执行你在事件派发线程上的逻辑。这意味着在您的方法返回之后才会执行重绘请求。如果你把你的代码放到另一个线程中那么这可能会解决问题,它会比使用 paintImmediately 好很多。

After reading your question again it occurs to me that you might be executing your logic on the event dispatch thread. This would mean that the repaint requests will not be executed until after your method returns. If you put your code into another thread then that will probably fix the problem and it will be a lot nicer than using paintImmediately.

void uiFunction() {
    new Thread() {
        public void run() {
            for(int i = 0; i < 10; i++) {
                final JButton b = buttons[i];
                SwingUtilities.invokeLater(new Runnable() {
                    b.setBackground(Color.WHITE);
                    b.repaint();
                }
                Thread.sleep(2000);
                SwingUtilities.invokeLater(new Runnable() {
                    b.setBackground(Color.GRAY);
                    b.repaint();
                }
            }
        }
    }.run();
}

有点儿肮脏,但希望它能让你知道从哪里开始。

It's a bit mucky but hopefully it gives you an idea of where to begin.

这篇关于在一个循环中重绘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆