java - 随着时间的推移定期调用重新绘制

标签 java swing repaint

所以,我有一个扩展 JPanel 的对象,并通过 PaintComponent 在矩阵中显示点。在特定条件下,矩阵的点可以移动、消失或倍增,我想自动显示它们随时间的演变,如下所示:

for(int i = 0; i < 100; ++i){

    matrix = calculateNextMatrix();    //Calculate possible movements, deaths or births of dots
    myGraphic.updateMatrix(matrix);    //Pass new dots to the JPanel object
    myGraphic.repaint();               //Draw new dots
    Thread.sleep(100);                 //Wait 0.1 seconds for next iteration (yes, this should be in a 
                                       //try-catch)
}

但是,我只在循环完成后的最后一次迭代中绘制,并且之前对 repaint() 的所有调用基本上都被忽略。如果我一次只进行一次迭代(例如,通过手动按下按钮),则没有问题。

有什么方法可以自动获得多个定期重绘调用吗?

最佳答案

我在我的库中遇到了 JComponent 的类似问题,我找到了一个使用 swing 计时器的解决方案,我报告了计时器的 java 描述

In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatch thread. However, you might use a general-purpose timer if you don't plan on touching the GUI from the timer, or need to perform lengthy processing.

You can use Swing timers in two ways:

  • To perform a task once, after a delay. For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
  • To perform a task repeatedly. For example, you might perform animation or update a component that displays progress toward a goal.

我认为您属于这种情况之一。

没有可重现的最小示例,我可以使用我的代码。

您应该创建 Swing 操作监听器,如下所示:

public class UpdateComponentListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            count += 10;
            timeLabel.setText(count + "");
            //The label call repaint
            //in your app you should be call the repaint

            //In your cases
            /*
                matrix = calculateNextMatrix();    //Calculate possible movements, deaths or births of dots
                myGraphic.updateMatrix(matrix);    //Pass new dots to the JPanel object
                myGraphic.repaint(); 
             */
        }
}

计时器构造函数输入延迟和 Action 监听器,因此您可以使用以下代码构建计时器:

Timer timer = new Timer(1000, new UpdateComponentListener());
timer.start();

您可以停止、重新启动计时器,因此您应该设置计时器的适当程度。

GUI 示例:

enter image description here

我写了这篇文章,在看到@camickr 评论后。我发布答案是因为我的工作已经完成,但是评论回答了您的问题。

我希望必须构建一个食物示例

关于java - 随着时间的推移定期调用重新绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159595/

相关文章:

java - 让程序等待直到单击按钮

java - 使用 JApplet 创建动画

java - repaint() 不调用 paintComponent()

java - 停止某些图形的重绘

java - Android:如何将图像插入到编辑文本中

java - 如何使用 jSTL 获取 HashMap 的大小

java - 事后如何添加依赖注入(inject)?

java - JFrame 更改边框颜色

java - 结果集的问题

java - Clojure :gen-class not working in Java app