0

使用以下代码,我想创建一个 Jpanel 通用组件并添加两个子组件,一个标签和一个 JTextField。我要添加组件,但它们没有左对齐。

(不,我不需要 GridBagLayout,但我试图用 GridBag 做一个基本示例。你能描述如何用 GridBag 而不是其他布局来做这个)。

public Component buildStatusComponent() {

    // Place the components on one line //
    final GridBagLayout layout = new GridBagLayout(); 
    final GridBagConstraints constraints = new GridBagConstraints();              
    final JPanel group = new JPanel(layout);

    constraints.anchor = GridBagConstraints.WEST;
    constraints.gridx = 0;        
    constraints.fill = GridBagConstraints.NONE;
    group.setAlignmentX(JComponent.LEFT_ALIGNMENT);
    group.add(new JLabel("Messages: "), constraints);

    constraints.gridx = 1;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    group.add(this.statusArea, constraints);        

    return group;
}

在此级别之上,我只是添加 JPanel 并水平填充。

constraints.gridy++;
constraints.fill = GridBagConstraints.HORIZONTAL;
this.add(this.buildStatusComponent(), constraints);
4

2 回答 2

1

您似乎没有完全使用 GridBagConstraints。而不是输入 group.setAlignmentX(JComponent.LEFT_ALIGNMENT) (我似乎从来没有为任何事情工作哈哈)只需使用 contraints.anchor = GridBagConstraints.WEST。

很多人不喜欢 GridBagLayout,但是一旦您了解它的工作原理,我发现它很容易使用。最难处理的是网格中对象的权重。

但特别是对于这个问题,您只想将组件锚定到具有 GridBagConstraint 常量的一侧,并依靠约束类来控制事情的去向。

编辑:好的,然后给他们重量。(虽然这可能解决不了问题嘿嘿)

constraints.weightx = 1d;

正在发生的事情是所有东西都有相同的重量,所以我相信它是均匀分布的。如果您想“塞满”这些项目,您可以在最后一个组件之后添加一个空 JPanel 并设置 fill = REMAINDER 并将其设为重量 1,其他组件设为重量 0。重量决定了一个组件可以“推动”多少'围绕另一个。

GridBagConstraints gbc = new GridBagConstraints();
JPanel p = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;

p.add(new JLabel("A"), gbc);
gbc.gridx++;
p.add(new JLabel("B"), gbc);
gbc.gridx++;
gbc.weightx = 1d;
gbc.fill = GridBagConstraints.REMAINDER;
p.add(new JPanel(), gbc);
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0d;
.... continue on filling stuff...

这是处理它的一种方法。稍微玩一下,直到你对它的工作原理有所了解是好的。

于 2009-12-18T18:58:24.703 回答
0

发布几行随机代码的问题是我们不知道如何使用代码的上下文。

Swing 教程中关于如何使用GridBagLayout的部分解释了为什么使用 weightx 约束很重要。由于您的父面板和子面板都使用 GridBagLayout,因此我们无法判断问题出在哪里。

如果您需要更多帮助,请发布说明问题的SSCCE 。

于 2009-12-18T20:32:15.517 回答