Java – Controling the size of components in Swing when their frame is resized


I have a simple form like this:

Username: ……….

Password: ……….

When the form is re-sized, I would expect JTextField (illustrated by ………) to be re-sized horizontally to fit the new width but not vertically (the same height for JTextField). Do we have any way to control this?


Best Solution

To answer your layout with the standard layout managers (except GridBag), nest layouts as follows:

    NORTH=BorderLayout   // keep everything at the top
        WEST=GridLayout(0,1) // the labels
            Label "UserName")
            Label "Password")
        CENTER=GridLayout(0,1) // the fields
            Text Field
            Password Field

Code would look something like

JPanel outer = new JPanel(new BorderLayout());
JPanel top = new JPanel(new BorderLayout());
JPanel labels = new JPanel(new GridLayout(0,1,3,3));
JPanel fields = new JPanel(new GridLayout(0,1,3,3));
outer.add(top, BorderLayout.NORTH);
top.add(labels, BorderLayout.WEST);
top.add(fields, BorderLayout.CENTER);
labels.add(new JLabel("Username"));
labels.add(new JLabel("Password"));
fields.add(new JTextField());
fields.add(new JPasswordField());

See for my (very old) explanation of how to nest layout managers like this.

GridBag is evil incarnate; just about impossible to figure out what the code is doing if you have more than a few components. To show how this would be done, though:

Insets i = new Insets(0,0,0,0);
p.setLayout(new GridBagLayout());
p.add(new JLabel("Username"), 
  new GridBagConstraints(0, 0, 1, 1, 0, 0, 
    GridBagConstraints.WEST, GridBagConstraints.NONE, i, 0, 0));
p.add(new JLabel("Password"), 
  new GridBagConstraints(0, 1, 1, 1, 0, 1, 
    GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, i, 0, 0));
p.add(new JTextField(), 
  new GridBagConstraints(1, 0, 1, 1, 1, 0, 
    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, i, 0, 0));
p.add(new JPasswordField(), 
  new GridBagConstraints(1, 1, 1, 1, 1, 1, 
    GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, i, 0, 0));

It works, but it's hard to "see" the layout in the code...