我有一个简单的形式,像这样:

用户名: ..........

密码:..........

调整表单大小时,我希望JTextField(由.....图示)会水平调整大小以适应新的宽度,但不能垂直调整大小(JTextField的高度相同)。我们有什么办法可以控制吗?

谢谢!

最佳答案

要使用标准布局管理器(GridBag除外)回答您的布局,请按以下方式嵌套布局:

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

代码看起来像
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));

它可以工作,但是很难在代码中“看到”布局...

10-07 19:21
查看更多