'How to implement properly a layer system using Graphics
so im doing a game using custom repaint on a jpanel, with the following implementation
public synchronized void paintComp(Graphics g) {
//Buffer is a BufferedImage and it Graphics object
EnumMap<Layer,Buffer> buffers = new EnumMap<>(Layer.class);
for (Layer layer : Layer.values()) {
buffers.put(layer, new Buffer(fsize.x, fsize.y));
}
this.ltime = System.currentTimeMillis();
//there i draw all the game content on buffers' g
this.scene.render(this, buffers, ltime, 0, 0);
//then i draw all layers in the right order
for (Buffer buf : buffers.values()) {
buf.g.finalize();
g.drawImage(buf.img, offset.x, offset.y, null);
}
}
basically, because the game content is organised as a tree, i wanted to draw content on layers then draw those layers on the screen in order to have a better ordering
issue is, i only know how to do that by instantiating 1 bufferedimage per layer each time that function is called, which considering the game is around 60fps and i have 18 layers, i create 1000 bufferedImage per second... is quite suboptimal :')
How could i implement that idea of buffers in a more proper way? i've heard of Rasters, VolatileImage and BufferStrategy but i just couldnt find the infos i needed nor work my way through the javadoc
Solution 1:[1]
Here are some ideas (not tested):
- Use a
CardLayoutput each panels not opaque - Use the
BetterGlassPaneand in thepaintComponentmethod use a for loop for paint all the layers using theGraphicsobject. https://github.com/kristian/better-glass-pane/blob/master/src/main/java/lc/kra/swing/BetterGlassPane.java - Use
JLayeredPanehttps://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/javax/swing/JLayeredPane.html - Use
JLayerhttps://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/javax/swing/JLayer.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anthony |
