Callum Singh
Callum Singh

Reputation: 79

GridLayout not working in JPanel

I'm trying to add a JButton to my JPanel multiple times using a GridLayout. For some reason though, every time I run the program it only shows 1 button.

Here's the code:

    jPLeft = new JPanel();
    jPLeft.setPreferredSize(new Dimension(600,500));
    jPLeft.setBackground(Color.WHITE);
    jPLeft.setLayout(new GridLayout(2,2));
    jPLeft.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    window.add(jPLeft, BorderLayout.CENTER);

    imageSand = new ImageIcon("..\\CSY1020\\src\\resources\\sand.jpg");
    jBSand = new JButton(imageSand);
    jPLeft.add(jBSand);
    jPLeft.add(jBSand);
    jPLeft.add(jBSand);
    jPLeft.add(jBSand);

Upvotes: 1

Views: 430

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35096

A Component can only be added once, and can only have 1 parent Container

imageSand = new ImageIcon("..\\CSY1020\\src\\resources\\sand.jpg");
for (int i = 0; i < 4; i++) {
    JButton jBSand = new JButton(imageSand);
    jPLeft.add(jBSand);
    jPLeft.add(jBSand);
    jPLeft.add(jBSand);
    jPLeft.add(jBSand);
}

Upvotes: 4

Related Questions