Using boxlayout, how do I get components to fill all available horizontal width?

If the container wants to force its components to all match its width, there are many alternatives that could do this better unless you need to use BoxLayout. One is the standard GridBagLayout. Given a container panel and three components a, b and c, the code would be:

panel.setLayout(new GridBagLayout());
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.HORIZONTAL;
cons.weightx = 1;
cons.gridx = 0;

panel.add(a, cons);
panel.add(b, cons);
panel.add(c, cons);

If the component wants to match its container's width, I would instead write the component's constructor to receive a reference to the container and override getPreferredSize to base the calculations on the passed-in component.


Because of the fact that BoxLayout is guided by a components preferred size, you could use:

JPanel middlePanel = new JPanel() {
   public Dimension getPreferredSize() {
       return outerPanel.getSize();
   };
};

taking the dimensions of the parent.

Tags:

Java

Swing