Search code examples
javaswinglayout-managerboxlayout

JPanel won't resize when using BoxLayout


I have a JPanel and set it as follows:

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

Then I add a JTextField, which takes up the entire panel:

JTextField field = new JTextField();
panel.add(field);

However, when I try to resize it:

panel.setPreferredSize(new Dimension(20,400));

Nothing happens. Why? I am using BoxLayout in order to put my JLabel and JTextField components in vertical order. If it's not possible to resize the panel, can I at least resize the JTextField so it does not take up the entire space?

Example:

import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class GUI extends JFrame 
{
    public GUI() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.setPreferredSize(new Dimension(20,400));
        JTextField field1 = new JTextField();
        JTextField field2 = new JTextField();
        panel.add(field1);
        panel.add(field2);
    }
}

Solution

  • can I at least resize the JTextField so it does not take up the entire space?

    A BoxLayout will resize a component to fill the space in the panel up to the maximum size of the component. A text field doesn't have a maximum size.

    You can prevent the text field from growing by controlling the maximum size:

    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    JTextField textField = new JTextField(10);
    textField.setMaximumSize( textField.getPreferredSize() );
    panel.add( textField );