Resize JPanel within a BoxLayout

1.3k views Asked by At

I have a JFrame which sets the content pane to a JPanel, which has a BoxLayout and two more JPanels, one is a "top bar" and the other is the content I want to work with. The top bar should occupy precisely the size I'm giving it and the content panel should take up the rest, but instead they both take half of the space. What am I doing wrong?

My classes:

public class TopBar extends JPanel
{
    public TopBar()
    {
        setLayout(new FlowLayout());
        setPreferredSize(new Dimension((int) (MyFrame.WIDTH / MyFrame.COMPRESSION), MyFrame.TOPBAR));
        add(new JButton("something"));
    }
}


public class ContentPanel extends JPanel
{   
    public ContentPanel()
    {
        setLayout(null);
    }
}

public class MyJpanel extends JPanel
{
    private JPanel topPanel;
    private JPanel contentPanel;

    public MyJpanel()
    {
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        topPanel = new TopBar();
        contentPanel = new ContentPanel();

        add(topPanel);
        add(contentPanel);
    }
}
3

There are 3 answers

2
Andrzej Kasp On

You should use setSize instead of setPreferredSize.

3
Mark Uivari On

My error was that I did not set the preferredSize of both panels, if i set the size of the contentPane aswell it'll work.

0
camickr On

but instead they both take half of the space

A BoxLayout will allocate extra space to each component up to the components maximum size.

The top bar should occupy precisely the size I'm giving it and the content panel should take up the rest,

Then don't use a BoxLayout. The default layout manager for the content pane of the JFrame is a BorderLayout, which does exactly what you want.

Read the section from the Swing tutorial on How to Use BorderLayout for more information and working examples.