我有个小问题。在动画期间执行paintComponent()方法时,我必须不断更新变量bgImage。但这需要很长的时间,这样动画就会慢下来。
问题的代码块:
public class ProblemClass extends JComponent {
    private static final int FRAME_FREQUENCY = 30;
    private final Timer animationTimer;
    public ProblemClass() {
        this.animationTimer = new Timer(1000 / FRAME_FREQUENCY, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                repaint(); // When the animation started is often invoked repaint()
            }
        });
    }
    // Other code...
    /** 
     * Start animation from another class
     */
    public void startAnimation() {
        this.animationTimer.start();
    }
    @Override 
    protected void paintComponent(Graphics g) { 
        // GraphicsUtils.gaussianBlur(...) it's a long-time operation
        BufferedImage bgImage = GraphicsUtils.gaussianBlur(AnotherClass.getBgImage()); 
        g2.drawImage(bgImage, 0, 0, null); 
        // Other code...
    }
}我在互联网上读到,我需要在并行线程(SwingWorker)中运行长任务,但我不知道如何在我的情况下这样做。我该如何解决这个问题?
P.S.对不起我的英语不好,这不是我的第一语言。
发布于 2014-09-17 16:46:52
您要做的最好的工作是在update方法之外进行图像更新,并且只在新图像准备好时重新绘制。取现有代码,并向图像添加一个持久引用,该引用将被绘制到JComponent reference方法上。然后让你的动画定时器做高斯模糊和更新你的图像。
public class ProblemClass extends JComponent {
    private static final int FRAME_FREQUENCY = 30;
    private final Timer animationTimer;
    //persistent reference to the image
    private BufferedImage bgImage;
    public ProblemClass() {
        this.animationTimer = new Timer(1000 / FRAME_FREQUENCY, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //Update the image on each call before repainting
                bgImage = GraphicsUtils.gaussianBlur(AnotherClass.getBgImage());
                repaint();
            }
        });
    }
    /** 
     * Start animation from another class
     */
    public void startAnimation() {
        this.animationTimer.start();
    }
    @Override
    protected void paintComponent(Graphics g2) {
        g2.drawImage(bgImage, 0, 0, null);
        // Other code...
    }
}https://stackoverflow.com/questions/25895498
复制相似问题