将JLabel放置在GridBagLayout的左上角

时间:2015-04-27 07:14:07

标签: java gridbaglayout

我正在使用GridBagLayout,我想将JLabel和textfield放在JPanel的左上角。我知道这个问题可能是重复的,但我找不到可以解释为什么我的代码最终居中的原因。

    JLabel user = new JLabel(ss[0]);
    JLabel av = new JLabel(ss[1]);
    JTextField ufield = new JTextField("");

    user.setBorder(BorderFactory.createLineBorder(Color.black));
    av.setBorder(BorderFactory.createLineBorder(Color.black));
    ufield.setBorder(BorderFactory.createLineBorder(Color.black));

    //User Label
    c.anchor = GridBagConstraints.NORTHWEST;
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.insets = new Insets(2, 0, 0, 2);
    p.add(user, c);

    //User TextField
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 5;
    c.gridheight = 1;
    c.weightx = 2;
    c.insets = new Insets(5, 1, 1, 5);
    p.add(ufield, c);

    //Available Label
    c.fill = GridBagConstraints.NORTHWEST;
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 1;
    c.insets = new Insets(5, 1, 1, 5);
    p.add(av, c);

    f.repaint();
    f.revalidate();

最终看起来像这样: enter image description here

我希望它靠近顶部而不是中心

1 个答案:

答案 0 :(得分:2)

JLabel和textfield实际上是在JPanel的左上角对齐,但是,JPanel不在JFrame的左上角(我猜测它是变量f),因此整体看来中心而不是左上角。

当您向其添加JPanel时,您必须控制JFrame的布局。您可以使用BorderLayout之类的方式来执行此操作:

f.getContentPane().setLayout(new BorderLayout());
f.add(p, BorderLayout.PAGE_START);