Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto resize JFrame according to content

I have created a custom JPanel that displays images (lets call it MyPanel), I have added this to JFrame's contentPane.

I want JFrame to be resized automatically to fit the MyPanel when image changes.

It looks like I need to call frame.pack() to do this. Calling pack() from MyPanel increases coupling so I don't want to do that.

To solve the issue I extended JFrame (lets call it MyFrame) and made MyFrame observer, and MyPanel observable. Whenever the image MyPanel is displaying changes it notifies the listeners, MyFrame for this instance. And then MyFrame calls pack() when it gets the notification.

Is there a smoother way of resizing JFrame according to its content?

like image 940
nimcap Avatar asked Nov 13 '09 16:11

nimcap


1 Answers

The solution you described seem reasonable.

Alternatively, whenever MyPanel changes its image, it can go find its parent Frame and then call pack() on it. If no such Frame exists, then don't do anything. No need to create additional classes, and its as loose a coupling as you are going to get. You can use SwingUtilities.getAncestorOfClass() to do this easily.

like image 86
Joel Carranza Avatar answered Oct 17 '22 02:10

Joel Carranza