Home > Back-end >  How to implement properly a layer system using Graphics
How to implement properly a layer system using Graphics

Time:02-11

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

CodePudding user response:

Well, i bypassed that problem by doing lists of things to draw instead of bufferedimages

CodePudding user response:

Here are some ideas (not tested):

  1. Use a CardLayout put each panels not opaque
  2. Use the BetterGlassPane and in the paintComponent method use a for loop for paint all the layers using the Graphics object. https://github.com/kristian/better-glass-pane/blob/master/src/main/java/lc/kra/swing/BetterGlassPane.java
  3. Use JLayeredPane https://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/javax/swing/JLayeredPane.html
  4. Use JLayer https://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/javax/swing/JLayer.html
  • Related