0

is there a way to show an image larger than the small imageIcon?

I have a 64x64 png image that I am trying to show on a button (take up the whole button).

but when I use

ImageIcon icon = new ImageIcon("somePath");
JButton btnBuildStructure = new JButton(icon);

the image that is shown is only the 16x16 in the top left corner of the image I want shown

how do I do this? I want it to look like this

enter image description here

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • *"is there a way to show an image larger than the small imageIcon?"* Sure. I've used images significantly larger than that in buttons. *"how do I do this?"* 1) For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). 2) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556). – Andrew Thompson Mar 09 '14 at 00:25
  • ..in fact, [here](http://stackoverflow.com/q/21142686/418556) is a Q&A (with screenshots) of 64x64 images (the chess pieces) being displayed in buttons (the places of the chess board). – Andrew Thompson Mar 09 '14 at 01:13

1 Answers1

1

The JButton should naturally size to an optimal preferred size that shows the entire icon. If this is not happening, then you are likely restricting the size of the JButton artificially. The solution: use the layout managers well, call pack() after adding all components and before setting the GUI visible, avoid null layouts, call revalidate() and repaint() on containers if you change any components, or their sizes or preferred sizes (such as if you change an icon while a program runs).

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I am drawing my button in a JPanel, and then I am adding it to the borderlayout of another JPanel, so I don't have access to the pack() method. unless I am thinking of the wrong method, isn't pack a JFrame method? – Joseph Dour Mar 08 '14 at 22:49
  • 1
    @JosephDour: What matters is that your top-level window is `packed()` after all components are added. For more help, consider creating and posting a [minimal example program](http://stackoverflow.com/help/mcve) (please click on and read the link). – Hovercraft Full Of Eels Mar 08 '14 at 22:52
  • 1
    *"I am drawing my button in a JPanel,.."* ***How?*** Answer in the form of a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). Hot-link to the image as advised above. – Andrew Thompson Mar 09 '14 at 01:15