JLabel over another JLabel not working

江枫思渺然 提交于 2019-12-02 10:19:17

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 */);
    }  
}

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<LocatedImage> 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!