Java双缓冲

时间:2011-05-07 23:31:27

标签: java swing awt doublebuffered

我正在开发一个项目,我已经尽可能多地阅读了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();
    }
}

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

2 个答案:

答案 0 :(得分:8)

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

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

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

    // draw stuff here

    bs.show(); // swap buffers
}

缺点是这种方法与事件驱动的渲染不能很好地混合。您通常必须选择其中一个。此外,getBufferStrategy仅在CanvasWindow中实施,使其与Swing组件不兼容。

教程可以找到hereherehere

答案 1 :(得分:2)

不要延长JPanel。延长JComponent。它实际上是相同的,并且具有较少的干扰代码。此外,您只需在paintComponent中执行绘图代码。如果您需要手动刷新组件,则使用component.redraw()。