Ronnie Stevenson
Ronnie Stevenson

Reputation: 27

Java - I get an error when i try to use a box layout

I was trying to create a frame using a box layout but I get a strange error:

Exception in thread "AWT-EventQueue-0" java.awt.AWTError: BoxLayout can't be shared.

here's the portion of code in my Jframe class that's probably causing the error:

    JLabel JL = new JLabel();
    PongPanel pp = new PongPanel();
    JPanel panel = new JPanel();
    BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
    setLayout(layout);
    panel.add(pp);
    panel.add(Box.createVerticalStrut(20));
    panel.add(JL);
    add(panel);

Upvotes: 0

Views: 89

Answers (1)

Reimeus
Reimeus

Reputation: 159844

The target container been assigned to the panel container in this statement

BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);

Use a different layout manager instance for the parent container replacing

setLayout(layout); 

with

panel.setLayout(layout); 

Read: How to Use BoxLayout

Upvotes: 2

Related Questions