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?
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.
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.
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With