2013-04-28 26 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

相关问题