views:

1315

answers:

1

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?

+1  A: 

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()][1] to do this easily

[1]: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html#getAncestorOfClass%28java.lang.Class, java.awt.Component)

Joel Carranza
Yeah, my approach was reasonable. Thanks for approval :)
nimcap