Search code examples
javaswinglayout-managerboxlayout

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

Solution

  • 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