Search code examples
javaswinglayout-managerboxlayout

How to make a JButton fill his parent BoxLayout


JFrame frame = new JFrame();
frame.setSize(400, 300);
JPanel panel = new JPanel() {{
    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    add(new JButton("button"));
    add(new JTextField("Text"));
}};

frame.setContentPane(panel);
frame.setVisible(true);

I want to make JButton fill parent layout like JTextField. So what property controlled it?


Solution

  • I want to make JButton fill parent layout like JTextField. So what property controlled it?

    BoxLayout respects the "maximum size" of the component.

    The maximum size of a button is its "preferred size", so if you want the button to grow you need to override the getMaximumSize() method of the button to return a dimension at least the size of your frame.

    Or as is mentioned in the comments you can use:

    1. a GridLayout to make all components the same size
    2. a GridBagLayout to allow components to grow as required.

    Read the section from the Swing tutorial on Using Layout Managers for more information on the above.