我刚开始使用双缓冲,一切正常,直到我想在屏幕上添加一个 JScrollPane,这样我以后可以做一些相机移动。除了 JScrollPane 的 ScrollBars,一切都很好(我的精灵)。我希望他们被展示出来!
但是,如果我调整窗口大小,滚动条会闪烁,所以我知道它们在那里!如果我足够快,我什至可以使用它们。他们为什么不出现在渲染?:(
这是问题的SSCCE:
public class BufferStrategyDemo extends JFrame
{
private BufferStrategy bufferStrategy;
private JPanel gameField;
private JScrollPane scroll;
public BufferStrategyDemo()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setPreferredSize(new Dimension(800, 600));
this.pack();
this.createBufferStrategy(2);
this.gameField = new JPanel();
this.gameField.setPreferredSize(new Dimension( 1400, 600 ));
this.scroll = new JScrollPane( gameField );
this.add( scroll, BorderLayout.CENTER );
this.setVisible( true );
this.bufferStrategy = this.getBufferStrategy();
setupGameFieldContent();
new Renderer( this, scroll , bufferStrategy ).start();
}
// Add some contents to gameField that shows up fine
private void setupGameFieldContent()
{
// For ( all my sprites )
// gameField.add( sprite );
}
private class Renderer extends Thread
{
private BufferStrategy bufferStrategy;
private JFrame window;
private JScrollPane scroll;
private Image imageOfGameField;
public Renderer( JFrame window, JScrollPane scroll, BufferStrategy bufferStrategy )
{
this.bufferStrategy = bufferStrategy;
this.window = window;
this.scroll = scroll;
}
public void run()
{
while ( true )
{
Graphics g = null;
try
{
g = bufferStrategy.getDrawGraphics();
drawSprites(g);
}
finally { g.dispose(); }
bufferStrategy.show(); // Shows everything except the scrollbars..
Toolkit.getDefaultToolkit().sync();
try { Thread.sleep( 1000/60 ) ; }
catch(InterruptedException ie) {}
}
}
private void drawSprites( Graphics g )
{
Graphics2D g2d=(Graphics2D)g;
//Also tried using the JPanels (gameField) createImage with same result
imageOfGameField = this.scroll.createImage(800, 600 );
Graphics screen = (Graphics2D)imageOfGameField.getGraphics();
/**
* For all my sprites, draw on the image
for ( Sprite current : sprites )
screen.drawImage( current.getImage(), current.getX(), current.getY(), current.getWidth() , current.getHeight(), null);
*/
g2d.drawImage( imageOfGameField, 0, 0 , null );
}
}
}