J86
J86

Reputation: 15257

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?

Upvotes: 4

Views: 2329

Answers (3)

Gene
Gene

Reputation: 46970

The usual way to reshape the enclosing native window, frame, or dialog to fit its contents is pack. See the example here. If you need access to e.g. a frame from a lightweight child, you can get it with

JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

Upvotes: 2

JohnnyO
JohnnyO

Reputation: 3068

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.

Upvotes: 5

MadProgrammer
MadProgrammer

Reputation: 347294

How to achieve this in WindowsBuilder I can't say, but when running, simply call pack on the frame

Upvotes: 2

Related Questions