Search code examples
javaswingjframejpanelboxlayout

Issue with JPanel, JFrame, BoxLayout


Hello I am having an issue with this. I am trying to create 2 panels. One with the labels stacked on top of each other in a BoxLayout and the other panel with TextFields also with a BoxLayout stacked up that correspond with the labels. I have tried various setups and keep getting errors.

I am setting Layout on JFrame as FlowLayout()

and using this to set the panels layoutManager

 leftPanel = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS));

This is something I have done before without issue. what is wrong now?

ERROR:

Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
at javax.swing.BoxLayout.checkContainer(BoxLayout.java:465)
at javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:249)
at javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:282)
at java.awt.Container.addImpl(Container.java:1125)
at java.awt.Container.add(Container.java:415)
at DataWriteExample.BuildLeftPanel(DataWriteExample.java:37)
at DataWriteExample.<init>(DataWriteExample.java:24)
at DataWriteExample.main(DataWriteExample.java:58)
Java Result: 1

Solution

  • You may try this instead:

    leftPanel = new JPanel();
    leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
    

    Update

    Problem with your code is:

    leftPanel = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS));
    -------------------------------------^
    // here `this` is not leftPanel, I believe its the JFrame instance
    // hence your getting the exception of cannot share the layout