我有一个显示动画的swing组件。动画帧是动态计算的(在BufferedImage
中)并以大约30fps的速度显示。
问题在于,它偶尔会产生半帧 - 在输出中给出非常明显的不连续性(在下面给出的测试用例中应该只是闪烁黑/白)。
谁能告诉我导致故障的原因以及如何解决这个问题?
请注意,运行此代码会产生快速闪烁的光线
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Animation extends JComponent {
FrameSource framesource;
public Animation(FrameSource fs)
{
this.framesource = fs;
setDoubleBuffered(true);
new Thread(new Runnable() {
public void run() {
while (true) {
framesource.computeNextFrame();
Animation.this.repaint();
try {Thread.sleep(30);} catch (InterruptedException e) {}
}
}
}).start();
}
public Dimension getPreferredSize() {return new Dimension(500,500);}
public void paintComponent(Graphics g) {
g.drawImage(framesource.getCurrentFrame(), 0,0,null);
}
}
class FrameSource
{
private BufferedImage currentframe;
public BufferedImage getCurrentFrame() {return currentframe;}
int frameCount = 0;
public void computeNextFrame()
{
BufferedImage nextFrame = new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB);
for (int x=0;x<500;x++)
for (int y=0;y<500;y++)
{
nextFrame.setRGB(x, y, (frameCount%2==0)?16777215:0);
}
frameCount++;
currentframe = nextFrame;
}
}
public class Flickertest {
public static void main(String[] args)
{
JFrame frame = new JFrame();
FrameSource fs = new FrameSource();
Animation a = new Animation(fs);
frame.getContentPane().add(a);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}