Java双缓冲

Cal*_*res 4 java swing doublebuffered awt

我正在研究一个项目,我已经尽可能多地阅读了java中的双缓冲.我想要做的是添加一个组件或面板或其他东西到我的JFrame,其中包含要绘制的双缓冲表面.我想尽可能使用硬件加速,否则使用常规软件渲染器.到目前为止我的代码看起来像这样:

  public class JFrameGame extends Game {

    protected final JFrame frame;
    protected final GamePanel panel;
    protected Graphics2D g2;

    public class GamePanel extends JPanel {

        public GamePanel() {
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            g2 = (Graphics2D)g;
            g2.clearRect(0, 0, getWidth(), getHeight());
        }
    }

    public JFrameGame() {
        super();
        gameLoop = new FixedGameLoop();

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new GamePanel();
        panel.setIgnoreRepaint(true);
        frame.add(panel);

        panel.setVisible(true);
        frame.setVisible(true);
    }

    @Override
    protected void Draw() {
        panel.repaint(); // aquire the graphics - can I acquire the graphics another way?
        super.Draw(); // draw components

        // draw stuff here

        // is the buffer automatically swapped?
    }


    @Override
    public void run() {
        super.run();
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个抽象游戏类和一个调用Update和Draw的游戏循环.现在,如果你看到我的评论,这是我关注的主要领域.有没有办法获取图形一次,而不是通过重绘和paintComponent,然后每次重绘分配一个变量?此外,此硬件是否默认加速?如果不是我该怎么做才能使硬件加速?

fin*_*nnw 8

如果您希望更好地控制窗口何时更新并利用硬件页面翻转(如果可用),则可以使用BufferStrategy该类.

您的Draw方法看起来像这样:

@Override
protected void Draw() {
    BufferStrategy bs = getBufferStrategy();
    Graphics g = bs.getDrawGraphics(); // acquire the graphics

    // draw stuff here

    bs.show(); // swap buffers
}
Run Code Online (Sandbox Code Playgroud)

缺点是这种方法与事件驱动的渲染不能很好地混合.您通常必须选择其中一个.也getBufferStrategy仅在实现中Canvas并且Window使其与Swing组件不兼容.

教程可以在这里,这里这里找到.