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

Periodic calls to repaint over time

所以,我有一个扩展 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 有一个类似的问题,我找到了一个带有摆动计时器的解决方案,我报告了计时器的 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(); 
             */
        }
}

计时器构造函数输入 delay 和动作侦听器,因此您可以使用以下代码构建计时器:

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

你可以停止,重新启动你的定时器,所以你应该设置定时器的适当程度。

GUI 示例:

我写了 post 并且在我看到@camickr 评论之后。我 post 回答是因为我的工作已经完成,但是评论回答了你的问题。

我希望有一个食物示例