【发布时间】:2014-09-17 16:12:41
【问题描述】:
我有一个小问题。在动画期间执行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.对不起,我的英语不好,这不是我的母语。
【问题讨论】:
-
以the documentation 开头。它应该非常简单——只要有一个
SwingWorker<BufferedImage, Void>。致电AnotherClass.getBgImage()并将结果传递给您的SwingWorker。在done()方法中调用get并将图像绘制到屏幕上。确保Swing组件和SwingWorker之间没有交互,因为这会破坏事情。 -
AnotherClass.getBgImage()的结果会在调用之间改变吗? -
一个完整的例子显示在here。
-
顺便说一句:
g2.drawImage(bgImage, 0, 0, null);应该是g2.drawImage(bgImage, 0, 0, this);,因为每个JComponent都是ImageObserver..
标签: java multithreading swing animation swingworker