JLabel over another JLabel not working

后端 未结 1 956
时光说笑
时光说笑 2021-01-28 10:40

I\'ve been trying to put a JLabel over another one for my Roguelike. Unfortunaly, it doesn\'t seems to work. Here\'s my code so far :

public void updateDraw(int          


        
1条回答
  •  时光说笑
    2021-01-28 10:46

    One Alternative

    Don't create your game environment using components (i.e. JLabels). Instead, you can paint all your game objects.

    For instance, if you're doing something like:

    JLabel[][] labelGrid = JLabel[][];
    ...
    ImageIcon icon = new ImageIcon(...);
    JLabel label = new JLabel(icon);
    ...
    for(... ; ... ; ...) {
       container.add(label);
    }
    

    You could instead get rid of the labels all together, and also use Images instead of ImageIcons, then you can just paint all the images to a single component surface. Maybe something like:

    public class GamePanel extends JPanel {
        Image[][] images = new Image[size][size];
        // init images
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image,/*  Crap! How do we know what location? Look Below */);
        }  
    }
    
    • Grapchics.drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)

    So to solve this problem with the locations (i.e. the x and y, oh and the size also), we could use some good old OOP abstractions. Create a class that wraps the image, the locations, and sizes. For example

    class LocatedImage {
        private Image image;
        private int x, y, width, height;
        private ImageObserver observer;
    
    
        public LocatedImage(Image image, int x, int y, int width, 
                                         int height, ImageObserver observer) {
            this.image = image;
            ...
        }
    
        public void draw(Graphics2D g2d) {
            g2d.drawImage(image, x, y, width, height, observer);
        }
    }
    

    Then you can use a bunch of instances of this class in your panel. Something like

    public class GamePanel extends JPanel {
        List imagesToDraw;
        // init images
        // e.g. imagesToDraw.add(new LocatedImage(img, 20, 20, 100, 100, this));
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g.create();
            for (LocatedImage image: imagesToDraw) {
                image.draw(g2d);
            }
            g2d.dispose();
        }  
    }
    

    Once you have this concept down, there are many different possibilities.

    • Have a look at Performing Custom Painting for some general ideas about painting.

    0 讨论(0)
提交回复
热议问题