【问题标题】:Placing JLabel in the top left corner of a GridBagLayout将 JLabel 放在 GridBagLayout 的左上角
【发布时间】:2015-04-27 15:54:13
【问题描述】:

我正在使用 GridBagLayout,我想将我的 JLabel 和文本字段放在我的 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();

这最终看起来像这样:

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

【问题讨论】:

  • 我在想,你的一个组件需要占用垂直可用空间,GridBagConstraints.weighty 设置为 1,然后你可以使用 GridBagConstraints.anchor 设置为 NORTH_EAST,假设标签在具有更多空间的单元格或调整 GridBagConistraints.fill 属性和标签垂直/水平对齐方式

标签: java gridbaglayout


【解决方案1】:

JLabel 和文本字段实际上在 JPanel 的左上角对齐,但是,JPanel 不在 JFrame 的左上角(我猜是变量 f),因此总体上它看起来居中而不是比左上角。

当您将 JPanel 添加到 JFrame 时,您必须控制它的布局。您可以使用BorderLayout 来做到这一点,例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多