2017-04-05 30 views

回答

2

有一种方法在交替列0,2,4,6至设定部件,而不在的GridBagLayout

号如果填充1,3,5与空部件组件没有为单元格定义,那么基本上它的大小为0.

布局无法猜测您希望“空列”的大小是多少。

也许你可以使用“insets”约束来给列之间的空间。

1

您可以用行高和列定义你的GridBagLayout宽度

int[] rowHeights = new int[] { 50, 50, 50}; 
int[] columnWidths = new int[] { 100, 100, 100, 100, 100}; 
GridBagLayout layout = new GridBagLayout(); 
layout.rowHeights = rowHeights; 
layout.columnWidths = columnWidths; 

添加使用GridBagConstraint组件如下

JPanel panel = new JPanel(); 
    panel.setLayout(layout); 

    JLabel label1 = new JLabel("Label 1"); 
    JLabel label2 = new JLabel("Label 2"); 
    JLabel label3 = new JLabel("Label 3"); 

    panel.add(label1, new GridBagConstraints(
      0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
      new Insets(0,0, 0, 0), 0, 0)); 

    panel.add(label2, new GridBagConstraints(
      2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
      new Insets(0,0, 0, 0), 0, 0)); 

    panel.add(label3, new GridBagConstraints(
      4, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
      new Insets(0,0, 0, 0), 0, 0));