我有一个小问题。在动画期间执行方法 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...
}
}
我在 Internet 上读到我需要在并行线程 (SwingWorker) 中运行长任务,但我不知道如何在我的情况下执行此操作。我该如何解决这个问题?
附言抱歉我的英语不好,这不是我的母语。
最佳答案
您要做的最好的事情是在 paint 方法之外更新图像,并且仅在新图像准备就绪时才重新绘制。采用您现有的代码,并添加对图像的持久引用,该图像被绘制到 JComponent
的每个绘制方法中。然后让您的动画计时器执行高斯模糊并更新您的图像。
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...
}
}
关于java - 方法减慢执行 paintComponent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25895498/