2013-04-28 29 views
0

我想列出標籤行中的列。我正在嘗試使用gridbaglayout,但我遇到了問題。當我展開窗口時,它不會展開。這是發生了什麼: enter image description hereGridBag面板不佔用所有的空間

我真正想要的是它的佈局中的單元格佔用1/5的空間,並將標籤轉移到單元格的左側大部分。

public static JPanel createLayout(int rows) { 
    JPanel product = new JPanel(new GridBagLayout()); 
    String[] lables = {"School", "Advanced #", "Novice #"}; 
    double weight = 1/(lables.length); 
    for (int i = 0; i < rows; i++) { 
     GridBagConstraints c = new GridBagConstraints(); 
     c.insets = new Insets(3, 3, 3, 3); 
     c.anchor = GridBagConstraints.WEST; 
     c.gridx = i; 
     c.weightx = weight; 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.anchor = GridBagConstraints.NORTHWEST; 
     for (int j = 0; j < lables.length; j++) { 

      JLabel l = new JLabel(lables[j]); 
      product.add(l, c); 
     } 
    } 
    return product; 
} 

public static void main(String[] args) throws IOException { 
    JFrame frame = new JFrame("Debate Calculator"); 
    JPanel debates = new JPanel(); 
    frame.add(createLayout(5), BorderLayout.CENTER); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
+1

使用JTable中...... – MadProgrammer 2013-04-28 21:52:16

回答

2

我相信問題是與你的體重計算...

double weight = 1/(lables.length); 

因爲1lables.length都是int類型,Java的自動轉換的結果爲int(這是0)。

相反,你可以試試...

double weight = 1d/(double)lables.length; 
+0

謝謝!只是一個側面問題:當我將ancor設置爲等於GridBagConstraints.CENTER並將其應用於標籤時,它不起作用。我還能如何將標籤集中在一個單元格中? – 2013-04-28 22:17:23

+0

這取決於'GridBagConstraint'的'fill'屬性,如果它是'HORIZONTAL'或'BOTH',那麼它自身的標籤將需要使用JLabel#setHorizo​​ntalAlignment(JLabel.CENTER)設置它的水平位置。 ',你也看看JLabel#setVerticalAlignment' – MadProgrammer 2013-04-28 23:31:28

相關問題