Java中连续复杂图像的动画绘制

问题描述:

我正在尝试在需要数千次计算的 JPanel 上绘制图像,并且我想为绘图的进程设置动画.即,不是一次性完成所有 100K 次绘制迭代,然后重新绘制 JPanel,我想在每次迭代后重新绘制,然后暂停几分之一秒,以便用户看到图像逐渐出现.但是,每次刷新 JPanel 都会擦除以前的绘图,因此我的方法不起作用.如何在不复制第 N 次迭代中的所有 (1..N-1) 计算的情况下执行此操作?

I am trying to draw an image on a JPanel that requires thousands of calculations, and I want to animate the progression of the drawing. I.e., instead of doing all 100K iterations of drawing in one go, and then repainting the JPanel, I want to repaint after each iteration, then pause for a fraction of a second, so the user sees the image gradually appearing. However, each refresh of the JPanel erases previous drawings, so my method doesn't work. How can I do this without replicating all (1..N-1) calculations on the Nth iteration?

考虑这个例子:我希望雪"逐渐出现在屏幕上.但是,此代码将仅显示第 100,000 个雪花",因为每次调用 repaint() 时,所有先前的雪花都会被删除.

Consider this example: I want "snow" to gradually appear on the screen. However, this code will only show the 100,000th "snowflake" as all previous ones get erased each time repaint() is called.

import javax.swing.*;
import java.awt.*;
import java.util.Random;

class spanel extends JPanel{    
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawLine(snow.x, snow.y, snow.x, snow.y);
    }
}

class snow extends Thread {

    static int x,y;
    Random r = new Random();

    public void run(){

        JFrame sboard = new JFrame();
        sboard.setSize(600,600);
        sboard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        spanel mypanel = new spanel();
        sboard.add(mypanel);
        sboard.setVisible(true);

        for (int i=0;i<100000;i++){
            x=r.nextInt(600);
            y=r.nextInt(600);

            sboard.repaint();    
            try {
                snow.sleep((long)10);
            } catch (InterruptedException e) {}; 
        } 
    }
}

public class SnowAnim {    
    public static void main(String[] args) {
        (new snow()).start();
    }
}

如何在不复制第 N 次迭代中的所有 (1..N-1) 计算的情况下执行此操作?

How can I do this without replicating all (1..N-1) calculations on the Nth iteration?

将它们添加到 BufferedImage,如本示例所示.

Add them to a BufferedImage as seen in this example.