Reputation: 585
I have a frame with a BorderLayout. In the BorderLayout's center there is a JPanel with a GridLayout. Sometimes I have to change this inner JPanel's GridLayout from 9x9 to 4x4 (or 16x16). But unfortunately the size of the cells stay the same. After manually resizing the frame, the Layout adapts the sizes and it looks right again. Here is what it looks like after changing to 4x4 and after resizing:
How can I force the inner Panel to automatically update? I tried repaint() on the inner panel (the one with the GridLayout) and the frame. At the moment i use this code which has some nasty side effects:
Dimension size = frame.getSize();
frame.setSize(new Dimension(size.height, size.width+1));
frame.setSize(size);
Is there any other ways to achieve this? Thanks in advance!
Upvotes: 3
Views: 2733
Reputation: 46841
After manually resizing the frame, the Layout adapts the sizes and it looks right again
Use frame.pack()
instead of setting frame.size()
that fits the components based on their preferred size.
Call frame.setVisible(true)
in the end after adding all the components.
Never call setSize()
for the components and leave it for Layout Manager to decide the size and position of the component.
Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Upvotes: 2