Java Double Buffering

I am working on a project and I read as much as possible about double buffering in java. I want to add a component or panel or something to my JFrame that contains a double buffered surface for drawing. I want to use hardware acceleration if possible, otherwise use a regular software renderer. My code looks like this:

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(); } } 

I created an abstract game class and a game loop that calls Update and Draw. Now, if you see my comments, this is my main problem. Is there a way to get the graphics once instead of going through repaint and paintComponent and then assign a variable to each redraw? Also, is this hardware acceleration by default? If not, what should I do to speed up its hardware?

+4
source share
2 answers

If you need more control when a window refreshes and use hardware page switching (if available), you can use BufferStrategy .

Your Draw method will look something like this:

 @Override protected void Draw() { BufferStrategy bs = getBufferStrategy(); Graphics g = bs.getDrawGraphics(); // acquire the graphics // draw stuff here bs.show(); // swap buffers } 

The disadvantage is that this approach does not go very well with event handling. Usually you have to choose one or the other. In addition, getBufferStrategy is only implemented in Canvas and Window , which makes it incompatible with Swing components.

The tutorials can be found here , here and here .

+8
source

Do not extend JPanel . Extend JComponent . This is pretty much the same and has less interfering code. In addition, you should make the drawing code only in paintComponent . If you need to manually update a component, you should use component.redraw( ).

+2
source

All Articles