简体   繁体   English

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

[英]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 ? 我一直想知道如何使用Image路径将ImageIcon设置为按钮并将其设置为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. 但是图像来自文件选择器,我可以使用getScaledInstance方法调整图片的大小。

How can i do this with image path since method getScaledInstance is undefined for the type String ? 由于类型String getScaledInstance方法未定义,我该如何使用图像路径执行此操作?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM