实际上,我已经知道如何更改按钮中的图像,但问题在于尺寸。
我更改了新图标,但我想保留大小,但此更改请对此提出一些建议。
我试图在更改图像以设置它之前获取按钮的尺寸,但尺寸不会缓存,并且在视觉上不会改变。
那是因为按钮使用了一个固定大小的图标。如果您想在 Java 中执行此操作,则必须
.getImage()
从您的 ImageIcon 对象或其他地方BufferedImage
BufferedImage
(具有您想要的大小)ImageIcon
使用新图像制作新图像ImageIcon
到您的按钮前三个步骤听起来很棘手,但还不错。这是一种帮助您入门的方法:
/**
* Gets a scaled version of an image.
*
* @param original0 original Image
* @param w0 int new width
* @param h0 int new height
* @return {@link java.awt.Image}
*/
public Image getImage(Image original0, int w0, int h0) {
// Check for sizes less than 1
w0 = (w0 < 1) ? 1 : w0;
h0 = (h0 < 1) ? 1 : h0;
// The new scaled image (empty for now.)
// Uses BufferedImage to support scaling and rendering.
final BufferedImage scaled = new BufferedImage(w0, h0, BufferedImage.TYPE_INT_ARGB);
// Create a canvas to draw with, in the new image.
final Graphics2D g2d = scaled.createGraphics();
// Try to prevent aliasing (if your image doesn't look good, read more about RenderingHints, they're not too hard)
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// Use the canvas to draw the scaled version into the empty BufferedImage
g2d.drawImage(original0, 0, 0, w0, h0, 0, 0, original0.getWidth(null), original.getHeight(null), null);
// Drawing is finished, no need for canvas anymore
g2d.dispose();
// Done!
return scaled;
}
但是,最好改为调整外部图标文件的大小,而不是给您的应用程序带来额外的工作。