Can I add a component to a specific grid cell when a GridLayout is used?

Roman picture Roman · Mar 24, 2010 · Viewed 74.9k times · Source

When I set the GridLayout to the JPanel and then add something, it is added subsequently in the "text order" (from left to right, from top to bottom). But I want to add an element to a specific cell (in the i-th row in the j-th column). Is it possible?

Answer

Rob Heiser picture Rob Heiser · Mar 24, 2010

No, you can't add components at a specific cell. What you can do is add empty JPanel objects and hold on to references to them in an array, then add components to them in any order you want.

Something like:

int i = 3;
int j = 4;
JPanel[][] panelHolder = new JPanel[i][j];    
setLayout(new GridLayout(i,j));

for(int m = 0; m < i; m++) {
   for(int n = 0; n < j; n++) {
      panelHolder[m][n] = new JPanel();
      add(panelHolder[m][n]);
   }
}

Then later, you can add directly to one of the JPanel objects:

panelHolder[2][3].add(new JButton("Foo"));