Trying to add label on panel

I am trying to put a label in every single panel I create but I only get the label in the last panel created. Its for a game of snakes and ladders and I am trying to initiate the board for the game. I need every panel to have a number.

    public InitBoard() {
        JPanel jPanel1 = new JPanel(new GridLayout(10, 10, 0, 0));
        JPanel[][] pa = new JPanel[10][10];
        //jPanel1.setSize(1024,1080);

        int counter=1;
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {

                JPanel tiles = new JPanel();
                tiles.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                number++;
                label1.setText(String.valueOf(number));
                tiles.add(label1);

                if(counter == 1) {
                    tiles.setBackground(Color.green);
                }
                if (counter == 2) {
                    tiles.setBackground(Color.red);
                }
                if(counter == 3 ){
                    tiles.setBackground(Color.cyan);
                }

                counter++;
                pa[i][j] = tiles;
                jPanel1.add(pa[i][j]);
                if(counter ==5){
                    counter =1;
                }
            }
        }

        add(jPanel1, BorderLayout.CENTER);
        setSize(960, 960);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}

Following image is shown when I run the file. Any help is appreciated in advance.

Upvotes: 0

Views: 67

Answers (1)

Candamir
Candamir

Reputation: 596

I can't see this from the code that you posted, but it seems that you are re-using the same JLabel instance (label1) for all the tiles. This somehow leads to the label being overwritten and re-used for all tiles except the last one.

Just use this line:

tiles.add(new JLabel(String.valueOf(number)));

instead of what you currently have:

label1.setText(String.valueOf(number));
tiles.add(label1);

Making this change, I got your code to work as intended, showing a number on every tile. If the numbers need to be stored somewhere or if you need to be able to change them later, you might want to create an array similar to the one you have for the JPanels (pa).

Upvotes: 1

Related Questions