4

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Nigel Thomas
  • 1,881
  • 8
  • 30
  • 50

1 Answers1

5

1.in the case that you put image as Icon / ImageIcon to the JLabel then

  • have to test for MaximumSize for JFrame that returned Toolkit for concrete monitor

  • if PreferedSize is lower than MaximumSize size then call JFrame#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 returns PreferredSize

    a) call JFrame#pack() if PreferedSize is lower than MaximumSize,

    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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 4
    Also consider `JScrollPane`, shown [here](http://stackoverflow.com/a/5129757/230513). – trashgod Aug 10 '12 at 11:06
  • 3
    Example to **Point 2** using ***Custom Painting*** is shown [here](http://stackoverflow.com/a/11372350/1057230) – nIcE cOw Aug 10 '12 at 11:08
  • 1
    don'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