0

I've created a GUI program with custom icons for buttons. I'm unable, however, to set the size of these buttons in Java, so they remain their original size, 230x227. I'm trying to get them to be around 20x20 so I used the following code:

classAlcBtn.setPreferredSize(new Dimension(20,20));
classAlcBtn.setIcon(new ImageIcon(getClass().getResource("Alchemist.png")));
classAlcBtn.setBorder(null);
classAlcBtn.setBorderPainted(false);
classAlcBtn.setContentAreaFilled(false);
classAlcBtn.setPressedIcon(
   new ImageIcon(getClass().getResource("alchemistClicked.png")));
classAlcBtn.setCursor(new Cursor(Cursor.HAND_CURSOR));

Is there a way to force these icons to size down, or do I have to size down the actual icon file? Thanks for any help.

Aubin
  • 14,617
  • 9
  • 61
  • 84
Ryan Cohan
  • 109
  • 1
  • 11
  • 1
    Can you size the buttons correctly without the icon? – rossum Feb 19 '17 at 10:02
  • 1
    *"230x227. I'm trying to get them to be around 20x20 so I used the following code:"* Those images are different aspect ratios. Is the idea to stretch, crop or pad them to fit the new aspect ratio? *"Is there a way to force these icons to size down,.."* Yes, **but..** *"..or do I have to size down the actual icon file?"* ..that would be the preferable option. There are good image editing programs for resizing images. To replicate that in Java is possible, but not trivial. Plus it means distributing a larger (in byte size) image file & taking more CPU time at app. start-up. – Andrew Thompson Feb 19 '17 at 11:25
  • @AndrewThompson yeah I just decided to resize the image file itself. Thanks for the information. – Ryan Cohan Feb 23 '17 at 07:30

1 Answers1

1

Assuming you can size down the buttons, without icons. So use the following method to size down the image, without changing the size of original file:

 ImageIcon icon = new ImageIcon("whatever.jpg");
 Image img = icon.getImage() ;  
 Image newImg = img.getScaledInstance( NEW_WIDTH, NEW_HEIGHT,  java.awt.Image.SCALE_SMOOTH ) ;  
 icon = new ImageIcon( newImg );

 ...

 classAlcBtn.setIcon(icon);

And if Button resizing itself is not working, then you can try using setMaximumSize() instead of setPreferredSize() method as following:

classAlcBtn.setMaximumSize(new Dimension(100,100));

See this for more info. about sizes. Hope this Helps:)

Community
  • 1
  • 1
Kaushal28
  • 5,377
  • 5
  • 41
  • 72