2009-12-18 63 views
0

使用下面的代码,我想创建一个Jpanel通用组件并添加两个子组件,一个Label和一个JTextField。我将添加组件,但它们不会对齐。 (不,我不需要GridBagLayout,但我试图用GridBag做一个基本的例子,你能描述如何用GridBag做这个而不是另一个布局)。JComponent和组件的左对齐

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

我们需要了解更多关于我认为的外部面板。但是如果我的怀疑是正确的,在组件上设置边界将帮助您查看布局错误的位置。 (提示:状态组件可能不会扩展以填充其“单元”,因为它没有weightx。) – PSpeed 2009-12-18 20:38:13

回答

1

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

很多人不喜欢GridBagLayout,但是一旦你了解了它的工作原理,我发现很容易工作。最难处理的是网格中物体的重量。

但是,具体来说,在这个问题中,您只需要将组件定位到GridBagConstraint常量的一侧,并依赖constraints类来控制事件发生的位置。

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

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... 

这是处理它的一种方法。一直玩下去,直到你感觉它是如何工作的是好的。

+0

我试过了,它没有从中心移动组件。 – 2009-12-18 19:05:29

0

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

Swing教程中关于如何使用GridBagLayout的部分解释了为什么使用weightx约束很重要。由于你的父母和小孩面板都使用GridBagLayout,所以我们无法确定问题出在哪里。

如果您需要更多帮助,请发送您的SSCCE来证明问题。