如何将ImageIcon 设置为JButton 并根据按钮的大小调整图片大小?

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

我一直想知道如何使用 Image 路径将 ImageIcon 设置为按钮并将其设置为 JButton

我可以根据按钮大小调整图片大小:

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

但图片来自文件选择器,我可以使用 getScaledInstance 方法调整图片大小。

由于类型 String 未定义方法 getScaledInstance,我如何使用图像路径执行此操作?

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