How can I you dynamically rearrange items in a gridlayout using java?
I need to rearrange items that are in my GridLayout
so when a JButton
is created dynamically, that the 开发者_JAVA技巧footer (i.e. JLabel
) stays at the bottom of the grid, and the dynamically created button goes right above the footer.
Is this possible? If so can I see an example, please?
My grid currently is a
new GridLayout(intIndex, 1);
where intIndex
is incremented every time a dynamic element is created.
Since it's a footer, you probably want to use BorderLayout
and keep the footer down at the bottom with BorderLayout.PAGE_END
. Then put your component with the GridLayout
in the center with BorderLayout.CENTER
. This way, your footer will always remain at the bottom and it won't interfere with the content, which you're now free to change to use any layout manager without affecting the footer.
This should be a good fix if your footer spans across the whole bottom, but if you're trying to make some sort of small footer in the bottom corner, then it'll be a little more difficult, but either way I'd suggest trying to keep the footer separate from the content.
I think there is more I can add, although one answer is accepted.
There are two interfaces for Layouts: LayoutManager
and LayoutManager2
. The second one extends the first one. So, all layout classes are inherited from LayoutManager
.
Now, LayoutManager2
lets you arrange your components according to some constraints. For example, in Shakedown's answer, BorderLayout.CENTER
is a constraint for BorderLayout
.
However, the layouts those implements only LayoutManager
does not accept constraints for a specific component. GridLayout
is such a layout. It will start adding components from top-left corner and continue towards right and go to next line when one line is full.
You may be interested about GridBagLayout
.
精彩评论