Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update JFrame size automatically after addition of new components

I have a JFrame with a JPanel inside (default stuff when using Window Builder Pro). In my code I am adding a new JPanel, but the outer JFrame fails to re-size to accomodate for the new components. So I have to drag manually.

Here is a screenshot:

enter image description here

How can I make it so that no matter what I put in there, the JFrame automatically updates its size to accommodate for the new Swing components?

like image 935
J86 Avatar asked Jan 13 '23 15:01

J86


1 Answers

After adding the new component, try calling

frame.pack() 

on the enclosing frame. The pack method will set the size of the frame based on the size of its underlying components. This is actually a method of the Window class, documentation available here

If you don't have a reference to the Window/Frame handy, an easy method is to call SwingUtilities.getWindowAncestor() on the panel after it has been added.

like image 64
JohnnyO Avatar answered Feb 04 '23 02:02

JohnnyO