Controlling component size in Swing when resizing a frame

I have a simple form:

Username:..........

Password:..........

When the shape is resized, I expect that JTextField(illustrated on .........) it will change horizontally to fit the new width, but not vertically (same height for JTextField). Do we have any way to control this?

Thanks!

+3
source share
3 answers

To respond to a layout using standard layout managers (except for the GridBag), plan layouts as follows:

BorderLayout
    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

The code would look 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());

. http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/ ( ) , , .

GridBag - ; , , . , :

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));

, "" ...

+2

.

(FlowLayout) .

, , GridBagLayout.

- setResizable(false).
- , , , , , .

, Java. .

+1

One easy way to manage it with one layout manager (for any use) would be to use MigLayout

JPanel panel = new JPanel(new MigLayout());

panel.add(firstNameLabel);
panel.add(firstNameTextField);
panel.add(lastNameLabel,       "gap unrelated");
panel.add(lastNameTextField,   "wrap");
panel.add(addressLabel);
panel.add(addressTextField,    "span, grow");

alt text http://www.miglayout.com/images/Form.png

+1
source

Source: https://habr.com/ru/post/1710191/


All Articles