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?
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.