0

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

}

1 Answers1

1

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"?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • _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"?_ Because in the real application the JLabel should be movabe across the JLayeredPanes. My demo just doesnt show that. –  Aug 11 '18 at 08:23
  • @Peter then you’re going to need to get rid of the layout manager and take control of it yourself – MadProgrammer Aug 11 '18 at 08:44
  • Well, with a little bit of effort, you could use a `GridBagLayout` on one `JLayeredPane` and simply update the `GridBagConstraints` for the `JLabel` to change it's cell position - something similar to [this example](https://stackoverflow.com/questions/11819669/absolute-positioning-graphic-jpanel-inside-jframe-blocked-by-blank-sections/11820847#11820847) - but yeah, you could also write your own layout manager - but I might be tempted to use a `GridBagLayout` first ;) – MadProgrammer Aug 11 '18 at 08:50