Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 907
Roman Avatar asked Mar 24 '10 17:03

Roman


People also ask

How do I add components to GridLayout?

To add Components to a GridLayout You do not (can not) use the row and column to tell where to add the components -- add them in starting at the top left and going across the row first.

How many GUI components can go into each cell with GridPane?

First we create the 7 GUI components that we'll be using in the GridPane layout. Next we create the layout itself, and add in some basic settings such as horizontal and vertical spacing between the components and padding between the layout and the window.

What is the difference between GridLayout and GridBagLayout?

A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each component is placed inside a rectangle whereas GridBagLayout is a flexible layout manager that aligns the components vertically and horizontally without requiring that the components be of the same size.


1 Answers

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")); 
like image 116
Rob Heiser Avatar answered Oct 09 '22 12:10

Rob Heiser