helpme
helpme

Reputation: 35

How can I add labels in specific cells of a GridLayout Panel in Java?

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();

        ImageIcon grassIcon = new ImageIcon("C:\\Users\\Pamvotis\\Desktop\\Project\\img\\icon.png"); 
        JLabel labels = new JLabel();

        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 6; col++) {
                gbc.gridx = col;
                gbc.gridy = row;

                CellPane cellPane = new CellPane();
                Border border = null;
                if (row < 9) {
                    if (col < 5) {
                        border = new MatteBorder(1, 1, 0, 0, Color.BLACK);
                    } else {
                        border = new MatteBorder(1, 1, 0, 1, Color.BLACK);
                    }
                } else {
                    if (col < 5) {
                        border = new MatteBorder(1, 1, 1, 0, Color.BLACK);
                    } else {
                        border = new MatteBorder(1, 1, 1, 1, Color.BLACK);
                    }
                }
                cellPane.setBorder(border);
                if ((row==0)&&((col==2)||(col==3))) { 
                    cellPane.setBackground(Color.RED);
                } else if ((row==9)&&((col==2)||(col==3))) { 
                    cellPane.setBackground(Color.WHITE);
                    labels = new JLabel(grassIcon);add(labels);
                } else {
                    cellPane.setBackground(Color.GREEN);
                }

                add(cellPane, gbc);
            }
        }
    }

So I have this code but the problem is every time I run the program the labels with the images are placed in the first line after the grid. It happens with every other try I've made the labels always appear on the first line of the grid or on the first line after the grid. Can anyone help me with this?

Upvotes: 1

Views: 1144

Answers (1)

camickr
camickr

Reputation: 324137

add(labels);

You are trying to add the labels to the panel without specifying the constraints. I believe default constraints will be used (whatever they are).

If you want to control the location of components then you need to specify the constraint with every add(...) statement.

Edit:

else if ((row==9)&&((col==2)||(col==3))) {cellPane.setBackground(Color.WHITE);labels = new JLabel(grassIcon);add(labels);}

I'm guessing you want:

else if ((row==9)&&((col==2)||(col==3))) 
{
    cellPane.setBackground(Color.WHITE);
    labels = new JLabel(grassIcon);
    //add(labels);
    cellPane.add(labels);
}
else 

Now you just need to make sure that "cellPane" uses a layout manager.

Upvotes: 1

Related Questions