I’m using javax.swing.JFrame to draw game animations using double buffer strategy.
First, I set up the frame.
JFrame frame = new JFrame();
frame.setVisible(true);
Now, I draw an object (let it be a circle, doesn’t matter) like this.
frame.createBufferStrategy(2);
bufferStrategy = frame.getBufferStrategy();
Graphics g = bufferStrategy.getDrawGraphics();
circle.draw(g);
bufferStrategy.show();
The problem is that the frame is not always fully set-up when the drawing takes place.
Seems like JFrame needs up to three steps in resizing itself, until it reaches it’s final size. That makes the drawing slide out of frame or hinders it to appear completely from time to time.
I already managed to delay things using SwingUtilities.invokeLater(). While this improved the result, there are still times when the drawing slides away / looks prematurely draw.
Any idea / strategy? Thanks in advance.
EDIT: Ok thanks so far. I didn’t mention that I write a little Pong game in the first place. Sorry for the confusion What I actually looked for was the right setup for accelerated game animations done in Java. While reading through the suggestions I found my question answered (though indirectly) here and this example made things clear for me.
A resume for this might be that for animating game graphics in Java, the first step is to get rid of the GUI logic overhead.
There’s an tutorial article about the difference of passive and active rendering. That might help to clean a newbie’s head…
I’ll answer this question myself because the question was a little misleading and I mixed things before I really knew the tools. The point I learned from this is, that for graphic programming in Java, there are two approaches: passive and active rendering.
While passive rendering happens from within the Event Dispatch Thread (EDT) and this is the process of letting the operating system and the VM determine the right time to draw components, it is not really possible or wanted to determine the exact moment when things get drawn. It’s just not the right approach for creating animated game graphics.
What you need instead is the active rendering stargetey, as documented in articles like this one. There you disable the rendering event dispatching entirely and actively redraw the whole scene via buffer flipping or blitting yourself (see BufferStrategy).
The difference between pasive and active rendering in AWT/Swing is in short explained at java tutorials.