1

I am using several JButtons in my frame and I want to set image in JButton. I am able to set the size of image using the following code.

Image img = icon.getImage() ;  
Image newimg = img.getScaledInstance( NEW_WIDTH, NEW_HEIGHT,  java.awt.Image.SCALE_SMOOTH ) ;  
icon = new ImageIcon( newimg );

And I also viewed the following link.

resizing a ImageIcon in a JButton

I am using WindowBuilder in my eclipse juno. And I set the image using setting the properties called icon and in the source code it generates the following code.

btnSave.setIcon(new ImageIcon(Patient_Detail.class.getResource("/Icons/download_icon.png")));

So, as my image size is comparatively bigger than my button size.

Is there any direct approach or method to set image size as the size of JButton using WindowBuider or adding any method to my current code?

Community
  • 1
  • 1
Nirav Kamani
  • 3,192
  • 7
  • 39
  • 68

1 Answers1

2

See this answer for an example of how to do it (presuming 'it' is 'have a button the same size as the button icon').

What you see below is actually 5 labels & 4 buttons each holding parts of an image. The red border can be seen around one of the buttons.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • there is no direct method to set image size???then taking buffered image i can also use the above code which is already working....to set image size... – Nirav Kamani Jul 26 '13 at 11:50
  • can you tell me why the following code is not working. it displays no image. JButton btnSave = new JButton(new ImageIcon(((new ImageIcon("/Icons/download_icon.png")).getImage()).getScaledInstance(102,51, java.awt.Image.SCALE_SMOOTH))); – Nirav Kamani Jul 26 '13 at 12:10
  • please who wins, will be works but have to calculating with delay caused by asynchronous output from ScalledInstance, load all object based on FileIO to local variables, then use a few methods implemented in API e.g. myButton.setIcon(myIconXxx); – mKorbel Jul 26 '13 at 12:17
  • I am not sure why that code (which I can barely read without code formatting) is not doing what you expect. If you have further questions about resizing the image, perhaps it would be best to start a new questions based purely on that. But for the best help, post an [SSCCE](http://sscce.org/) that hot links to a small (in bytes) image, like I did in the linked answer. Also note that many people warn against using `getScaledInstance(..)` as detailed in [The Perils of Image.getScaledInstance()](https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html). – Andrew Thompson Jul 26 '13 at 12:59