I recently stumbled upon a problem when attempting to create an overlay for my frame. The frame consists of 2 panels, a GamePanel
and an OverlayPanel
, each with their own paint
methods. I seperated these in order to keep my code cleaner and for efficiency. The problem I'm having now, though, is that my paintComponent
methods are overlapping each other, causing only one painted panel to be visible at a time.
I understand that this is caused most likely due to the fact that both panels cover the entirety of the screen. What is being painted on the OverlayPanel
, however, only covers a part of the screen.
The goal is that the GamePanel
will draw a map of some sort and the OverlayPanel
will then draw something such as a rectangle at a given location on top of this map.
Is my approach to this wrong, or is there something I'm missing?
Is my approach to this wrong, ..
Yes. It is possible to separate drawing operations into separate methods in separate classes, yet still have the entire paint operation done by a single method.
Imagine there is a Map
class with a draw(Graphics2D)
method, and a RectangularPlayer
class also with a draw(Graphics2D)
method. Each class knows how to draw its own parts to a common graphics instance. In the paintComponent(Graphics)
method of the GameField
class, call the relevant draw methods of the map and player classes, as well as any other game elements that need to be rendered.