使用 Java 的 JComponent repaint() [英] Using Java's JComponent repaint()

查看:72
本文介绍了使用 Java 的 JComponent repaint()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写一个简单的 Game of Life 程序,但在让它动画化时遇到了一些麻烦.我有一个名为 LifeDrawJComponent 类,它使用以下绘制方法显示像素网格:

I'm writing a simple Game of Life program in Java and am having a bit of trouble getting it to animate. I've got a JComponent class called LifeDraw, which displays a grid of pixels, with the following paint method:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    for (int y = 0; y < lGrid.getHeight(); y++) {
        for (int x = 0; x < lGrid.getWidth(); x++) {
            if (lGrid.getCell(x,y) == 1) {
                g.setColor(Color.red);
                g.fillRect(x * lGrid.getSqSize(), y * lGrid.getSqSize(), lGrid.getSqSize(), lGrid.getSqSize());
            } else {
                g.setColor(Color.white);
                g.fillRect(x * lGrid.getSqSize(), y * lGrid.getSqSize(), lGrid.getSqSize(), lGrid.getSqSize());
            }
        }
    }
}

然后是另一个具有方法 run() 的类 LifeGrid,该方法在调用时将更新一代的像素网格,然后调用 LifeDraw.重绘().但是,如果我尝试在循环中调用 run()JComponent 在循环完成之前不会重新绘制,因此所有显示的都是第一代和最后一个.我认为它可能只是更新太快而无法重新绘制,因此我尝试在迭代之间使用 Thread.sleep() 但仍然遇到相同的问题.理论上(或者至少我希望它会),它应该在每次迭代之间重新绘制组件并显示像素变化的动画.

And then another class LifeGrid that has a method run(), which when called will update the grid of pixels for one generation and then call LifeDraw.repaint(). However, if I try to call run() in a loop, the JComponent doesn't repaint until the loop is finished so all that is ever displayed is the first generation and the last one. I figured it was probably just updating too quickly to repaint, so I tried using Thread.sleep() between iterations but still had the same problem. Theoretically (or at least I was hoping it would), it should repaint the component between each iteration and display an animation of the pixels changing.

我不太熟悉 Java GUI,因此非常感谢您的帮助.希望我已经解释得够清楚了,否则请告诉我!

I'm not that well versed in Java GUI, so any help would be really appreciated. Hopefully I've explained it clearly enough, let me know otherwise!

推荐答案

我不知道它是否能解决您的问题,但您可以尝试从 定时器 而不是简单的 for 或 while 循环.

I don't know if it would solve your problem, but you could try calling run() from a Timer instead of a simple for or while loop.

这篇关于使用 Java 的 JComponent repaint()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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