I need to display an image in a JFrame. How can I make the window size to be automatically adjusted based on the size of the image.
1 Answers
1.in the case that you put image as Icon / ImageIcon to the JLabel then
have to test for
MaximumSizeforJFramethat returned Toolkit for concrete monitorif
PreferedSizeis lower thanMaximumSizesize then callJFrame#pack()otherwise have to call
setSize()
2.in the case that you put image as Icon / ImageIcon by using Custom Painting to the JComponent, JPanel, JLabel e.i. then
then this
JComponent must to returnsPreferredSizea) call
JFrame#pack()ifPreferedSizeis lower thanMaximumSize,b) otherwise have to call
JFrame#setSize()c) by assume that you don't use
Image#getScalledInstance
3.I'd be to use Icon in the JLabel, there is only one issue that image can be smaller then expected size on the screen, but no issue with that, is pretty possible to centering image to the JLabel.CENTER to the JLabel
- 109,525
- 20
- 134
- 319
-
4Also consider `JScrollPane`, shown [here](http://stackoverflow.com/a/5129757/230513). – trashgod Aug 10 '12 at 11:06
-
3Example to **Point 2** using ***Custom Painting*** is shown [here](http://stackoverflow.com/a/11372350/1057230) – nIcE cOw Aug 10 '12 at 11:08
-
1don't quite understand the overall logic: a) typically, max is waaay big (so it's safe enough to simply ignore in first approximation) and waayy greater than pref b) a JLabel returns a reasonable size for pref, pack is all that's needed c) _otherwise_ would be pref > max which would be an illegalState that has to be fixed (instead of forcing the actual size to larger (not sure if the frame would oblige) 1. and 2. look very mush the same (except for manual painting and custom override of getPref) – kleopatra Aug 10 '12 at 12:41