Search code examples
javaswingalignmentjpanelboxlayout

Java BoxLayout gives Incorrect Results


I've got two JPanels that I want to be arranged, one on top of the other, inside of a larger JPanel. "panel_controls" overrides .getPreferredSize(). Code:

public final class GUIPanelMain extends JPanel {
    //...

    private JPanel panel_images;
    private JPanel panel_controls;

    //...

    private void addPanels() {
        new BoxLayout(this,BoxLayout.Y_AXIS); //Bleh!  Still is horizontal!
        this.add(panel_images);
        this.add(panel_controls);
    }

    //...
}

Unfortunately, the layout is set up horizontally anyway. It's only when I resize the JPanel that the components all go in the right places (vertically, in this case).

I read the following in the documentation: "BoxLayout attempts to make all components in the column as wide as the widest component. If that fails, it aligns them horizontally according to their X alignments"

What are the conditions for failure, then? How can I force it to be vertically aligned?

Thanks,


Solution

  • try

    this.setLayout( new BoxLayout(this, BoxLayout.Y_AXIS));
    

    You are basically creating a new instance of BoxLayout that goes unused and unreferenced.