我正在使用我自己的双缓冲进行渲染循环,我没有JPanel,而是JFrame(据我所知,JPanel自动双缓冲)。我的问题是,当我叫super时。画图(g)它使我的屏幕闪烁。当我把它评论出来时,它就消失了。
我创建一个BuffereImage并抓取它的图形2D,然后每个渲染循环我用纯色刷新图像并调用repaint()。在paint方法中,我调用super并使用paint()方法的图形绘制图像。即使渲染1 fps,这也会导致屏幕闪烁。
public void run()
{
long startTime;
long runTime;
double residualTime = 0;
while(isRunning)
{
startTime = System.nanoTime();
**update.update();**
render.render();
runTime = System.nanoTime() - startTime;
if(runTime < 1e9/fpsTarget)
{
Double sleepTime = (1e9/fpsTarget - runTime) / 1e6;
residualTime += sleepTime % 1;
sleepTime -= sleepTime % 1;
if(residualTime > 1)
{
sleepTime++;
residualTime--;
}
try
{
sleep(sleepTime.longValue());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
/*
System.out.println("\n Run time: " + runTime / 1e6);
System.out.println(" Sleep time: " + sleepTime);
System.out.println("Residual Time: " + residualTime);
*/
}
}
//fps(startTime);
}
}
public class Render
{
private Screen screen;
Graphics2D graphics;
BufferedImage image;
public Render()
{
screen = new Screen();
image = new BufferedImage(screen.getWidth(), screen.getHeight(), BufferedImage.TYPE_INT_RGB);
graphics = image.createGraphics();
}
public void render()
{
flush();
screen.setImage(image);
screen.repaint();
}
private void flush()
{
graphics.setPaint(Color.BLUE);
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
}
}
public class Screen extends JFrame
{
private BufferedImage image;
public Screen()
{
super(TITLE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLocation(300, 150);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image, 0, 0, null);
}
public void setImage(BufferedImage image)
{
this.image = image;
}
我以前尝试过添加JPanel并通过paintComponent()进行渲染,但也遇到了同样的问题。任何想法和建议都会很有帮助!
编辑-已解决
奇怪的是,之前我调用repaint()时,删除了super。paint()也解决了这个问题。知道为什么吗?