2015-06-19 110 views
0

我一直在讨论GridBagLayout,并且遇到了一些麻烦。首先,我试图让标签在左上角我完成下手:GridBagLayout对齐标签

JPanel right = new JPanel(new GridBagLayout()); 
    right.setPreferredSize(new Dimension(333,600)); 

    GridBagConstraints gbc = new GridBagConstraints(); 
    gbc.anchor = GridBagConstraints.NORTHWEST; 

    JLabel testLabel = new JLabel(); 
    testLabel.setText("Test"); 
    gbc.gridx = 0; 
    gbc.gridy = 0; 
    gbc.weighty = 1; 
    gbc.weightx = 1; 
    right.add(testLabel, gbc); 

现在我想直接在这个添加另一个标签:

JLabel test2Label = new JLabel(); 
    test2Label.setText("test2"); 
    gbc.gridx = 0; 
    gbc.gridy = 1; 
    gbc.weighty = 1; 
    gbc.weightx = 1; 
    right.add(test2Label, gbc); 

,而不是直接把它在第一个之下它将它放置在面板的中间。它因为重量和重量我想,但如果我改变这些,那么它不会把标签放在左上角。我怎样才能使它工作?对不起,如果不清楚英语不是我最好的语言,所以让我知道你是否需要我澄清。 - 谢谢

回答

0

如果我正确理解你,下面的代码应该是答案。 weightx和weighty决定如何将组件中的可用空间分配给其子组件 - 值越大,空间越多(详细信息请参阅:Weightx and Weighty in Java GridBagLayout),但如果将所有组件的值都设置为零,则它们都将居中。

所以在你的情况下,最好的解决方案将给第二个组件留下整个左侧空间。

GridBagConstraints gbc = new GridBagConstraints(); 
gbc.anchor = GridBagConstraints.NORTHWEST; 

JLabel testLabel = new JLabel(); 
testLabel.setText("Test"); 
gbc.gridx = 0; 
gbc.gridy = 0; 
gbc.weighty = 0; 
gbc.weightx = 0; 
right.add(testLabel, gbc); 

JLabel test2Label = new JLabel(); 
test2Label.setText("test2"); 
gbc.gridx = 0; 
gbc.gridy = 1; 
gbc.weighty = 1; 
gbc.weightx = 1; 
right.add(test2Label, gbc); 
+0

好吧我想我明白了为什么这样的作品。谢谢 –