2013-03-12 88 views
0

我想要使用GridBagLayout构建一个数组的元素。创建元素工作得很好。问题是布局管理器被忽略或约束不能正确应用,反正按钮排列就好像根本没有布局管理器一样。那么我需要做什么,它看起来像一张桌子?使用数组元素填充GridBagLayout

在此先感谢!

旁注:不,JTable不是一个选项。在我的应用程序中,只有一些按钮是实际创建的。

编辑:我发现了这个问题。我简单地忘记了“setLayout(gbl);”愚蠢的我。

//(includes) 

public class GUI { 
    public static void main (String[] args) { 
     JFrame frame = new JFrame(); 
     frame.add (new MyPanel(5, 4); 
     frame.setVisible(true); 
    } 

    private class MyPanel() extends JPanel { 
     public MyPanel (int x, int y) { 
      GridBagLayout gbl = new GridBagLayout(); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      setLayout (gbl); 

      JButton[][] buttons = new JButton[x][y]; 
      for (int i=0; i<x; i++) { 
       for (int j=0; j<y; j++) { 
        buttons[i][j] = new JButton("a"+i+j); 
        gbc.gridx = j; gbc.gridy = i; 
        gbl.setConstraints(buttons[i][j], gbc); 
        add (buttons[i][j]); 
       } 
      } 
     } 
    } 
} 
+0

请发表包含一个完整的,独立,可运行的例子。 – 2013-03-12 18:23:37

回答

0

您也可以考虑使用MigLayout,代码简单,易于维护:

public class MyPanel extends JPanel { 
    public MyPanel(int x, int y) { 
     setLayout(new MigLayout("wrap " + x)); 

     JButton[][] buttons = new JButton[x][y]; 
     for (int i = 0; i < x; i++) { 
      for (int j = 0; j < y; j++) { 
       buttons[i][j] = new JButton("a" + i + j); 
       add(buttons[i][j]); 
      } 
     } 
    } 
}