2015-06-19 118 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

好吧我想我明白了爲什麼這樣的作品。謝謝 –