Search code examples
javacomponentsjlabelgrid-layout

How do you overlap components in the grid layout?


For my senior project I am coding a game in Java. It has a grid of square that you need to navigate through in order to complete the goal. I found that grid layout does what I need it to except that I can't seem to get the main character to overlap (go on top of) the spaces on the level. I basically want to be able to overlap the icon 'start' with any other icon such as 'empty'. I haven't found a good way of doing this yet (granted I am new at this). I would like to either know the way to do this, or even if I can't. If I can't do this, I ask that you leave a link that will demonstrate a way that I can achieve my goal.

Below is a small clip out of the code that relates to setting the level up. When When I try to add the main character to a specified area on the grid, it simply pushes everything up 1.

public loadWindow() throws IOException {

    try{
        level = new FileReader("levels/debug1.txt");

        while ((type = level.read()) != -1){
                if (type == 'a'){
                    icon = start;}
                if (type == 'b'){
                    icon = empty;}

                //Includes the rest of the if statemets

                if (type == 'x'){
                    test = false;}


                if (test == true){
                    JLabel spot = new JLabel(new ImageIcon(icon));
                    add(spot);}
            }

        } finally {
            if (level != null){
                level.close();
        }
    }
}

Solution

  • Use JLayeredPane where you can add various components like JButton, JPanel, etc.. at different layers (Default, Palette, Modal, PopUp, Drag) of JLayeredPane.

    For adding JButton to the 'Default Layer', use: jlayeredpane.add(jbutton, JLayeredPane.DEFAULT_LAYER);