I’m experienced in Java and I’ve done a little with Swing (form type apps), but I’ve never needed more power than that so I don’t know much about what’s going on under the hood GUI-wise. Here is what I’ve gleaned from the little bit of reading I’ve been doing. I’m sure it’s off.
In writing a space invaders type game, two approaches I thought of would be:
- Create one big component and code for all the incremental painting and layering.
- Create a bunch of nested absolutely positioned JPanels in a JLayeredPane that contains text and images, then call repaint() on just the ones that might need to be redrawn. Then override paintComponent() (not sure if previous content is cleared automatically or not). From what I read, this would handle the layering and redrawing of components without having to redraw the whole screen.
Is this correct? If so, which method is better suited for the project?
One thing to really consider when it comes down to game programming in Java is to switch to Active Rendering.
as we know, Swing takes care of rendering in another thread, called Event Dispatch Thread. This is known as passive rendering, because you don’t really render your own visual components, but you define how your app will look like and Swing actually draws it when he wants.
Games usually work in Full Screen mode and often require more control over the “when”, “how” and “what” will be drawn. This is called active rendering. In this case, you have to disable the Even Dispatch Thread and do the rendering on your own.
It all makes sense, because games often work inside a big loop. One example of a game loop is:
There are many sources, but I can suggest this first reading to clarify on that: Passive vs Active Rendering