2013-03-12 93 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]); 
      } 
     } 
    } 
}