Search code examples
javaimageswingimageicon

How to set an ImageIcon to a JButton and resize the picture according to the button's size?


I've been wondering how can I set an ImageIcon to a button using the Image path and set it to a JButton?

I can resize the image's size according to the buttons size:

frontViewImageFile = fc.getSelectedFile();
MainFrame.btnFrontView.setIcon(new ImageIcon(ImageIO.read(
    frontViewImageFile).getScaledInstance(150, 150, Image.SCALE_SMOOTH)));  

But the image came from a file chooser and I can use getScaledInstance method to resize the picture.

How can i do this with image path since method getScaledInstance is undefined for the type String?


Solution

  • ImageIcon icon = ...;
    JButton b = ...;
    Image im = icon.getImage();
    Image im2 = im.getScaledInstance(b.getWidth(), b.getHeight(), ...);
    b.setIcon(new ImageIcon(im2));