Search code examples
javaswingjlayeredpane

JButton "disappears" although it is on another Layer than JLabel


I am currently making a chess-like board game, so I made a 11*11 Field. On each field should be a JButton (on the default layer) and and on a higher layer that a movable JLabel. But the label pushes the button still away. Here is the simplified code:

public class Demo {

    public static void main(String[] args) {

        ImageIcon image = new ImageIcon("C:src\\myImage.png");

        JFrame frame = new JFrame();

        JPanel mainPanel = new JPanel();

        JLayeredPane[] tileLayeredPane = new JLayeredPane[121];

        JButton button = new JButton();

        JLabel label = new JLabel();

        label.setIcon(image);

        button.setText("I am not visible!");

        for (int i = 0; i < tileLayeredPane.length; i++) { // creates 121 JLabels

            tileLayeredPane[i] = new JLayeredPane();

            tileLayeredPane[i].setLayout(new BoxLayout(tileLayeredPane[i], BoxLayout.Y_AXIS));
            tileLayeredPane[i].setOpaque(true);
        } 

        tileLayeredPane[0].add(button, JLayeredPane.DEFAULT_LAYER);
        tileLayeredPane[0].add(label, JLayeredPane.PALETTE_LAYER);

        mainPanel.setLayout(new GridLayout(11, 11));

        for(int i = 0; i < 121; i++) {

            mainPanel.add(tileLayeredPane[i]);
        }

        frame.add(mainPanel);
        frame.setVisible(true);
    }

}

Solution

  • On each field should be a JButton (on the default layer) and and on a higher layer that a movable JLabel

    Yes, because you're using a BoxLayout on the JLayeredPane, which is deciding how the components should be laid out - the JLayeredPane only effects the order in which components are painted, not how they are laid out

    I'm "guessing" that you're trying to put the label over the top of the button, which begs the question of "why aren't you using the buttons inbuilt image support"?