I'm trying to make a game with Swing and I need to make a board with players on the board, so I've used the JLayeredPane
. At layer 0 I drew the board and then on layer 1 I've painted the players.
This works well but the problem is when I redraw layer 1 (e.g. change the position of a given player) the performance is very bad. My assumption is it's repainting the background board again and this is causing the issue.
Here's the code:
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.add(boardView, new Integer(0));
layeredPane.add(creepsView, new Integer(1));
creepsView
and boardView
override the paint method and when changes to the state of the creeps happens, it's calling the creepsView.repaint()
method, but then the boardview.paint()
is called by the JLayeredPane and I don't understand why. How can I avoid it? (I don't want to redraw the things that didn't change).
I guess it's because it's repainting the background board again.
I doubt that is the problem since painting an image that is loaded into memory is very efficient.
, it's calling the creepsView.repaint() method and then the boardview.paint is called by the JLayeredPane
In order for you to see the background that means the panel containing the players must be transparent. This means when you repaint the player panel, the background panel must also be repainted to make sure there are no painting artifacts. For example, the player must be removed from its old position and painting in the new position.
You can try to make the painting more efficient by only painting the affected area of the panel. That is instead of repainting the entire player panel you only repaint the player at its old position and at its new position. Read the section from the Swing tutorial on Custom Painting for an example of this approach. ThemoveSquare(...)
method shows how this approach works.