循环绘制组件 [英] repaint components in a loop

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

问题描述

我正在创建一个简单的游戏,我想在每一步之后重新粉刷木板.因此,在我调用move()之后,我想做的是这样的:(顺便说一句,一个View是一个Jpiece,它保存了块;由于块的数量在移动后发生了变化,因此需要重新绘制) /p>

I'm creating a simple game and I'd like to repaint the board after every move. So, after I call move(), what I would like to do is this: (by the way, a View is a JComponent that holds pieces; since the number of pieces has changed after the move, it needs to be repainted)

for(View v : views){            
        v.repaint();
    }

它不起作用.当我在单个View上调用repaint()时,它可以正常工作.我尝试使用paintImmediatelyrevalidateupdate ...在循环中没有任何作用.

It's not working. When I call repaint() on a single View, it works fine. I tried using paintImmediately, and revalidate, and update... nothing works within the loop.

有什么想法吗?预先感谢.

Any ideas? Thanks in advance.

我应该补充一点,当调整窗口大小时,确实会调用repaint(),所以我知道View的paintComponent方法是有效的并且可以工作.只是没有从循环中调用它.当调试器逐步执行循环时,它不会输入repaint(),并且屏幕上没有任何反应.

I should add that repaint() does get called when the window is resized, so I know that View's paintComponent method is valid and works. It's just not being called from the loop. When the debugger steps through the loop, it does not enter repaint() and nothing happens to the screen.

推荐答案

与UI相关的所有事情都必须在事件分发线程(EDT)中调用:

Everything related to the UI must be called in the Event Dispatching Thread (EDT):

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        for(View v : views){
            v.repaint();
        }
    }
});

您还可以使用 invokeAndWait 而不是

You can also use invokeAndWait instead of invokeLater. You should read on the EDT if you want a responsive application.

例如,如果将actionListener添加到按钮中,则在EDT线程中执行在actionListener中执行的代码,因此必须限制进程,否则UI将停止响应.

For example, if you add an actionListener to a button, the code executed in that actionListener is executed in the EDT thread, so you must limit the process or you UI will stop responding.

此外,请查看 查看全文

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