实际上,我已经知道如何更改按钮中的图像,但问题在于尺寸。
我换了新图标,但我想保留尺寸,但是这个改变请一些建议。
我尝试在更改图像之前获取按钮的尺寸然后设置它但是尺寸没有缓存,并且它在视觉上没有变化。
答案 0 :(得分:3)
那是因为按钮使用的图标是固定大小的。如果你想在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;
}
但是,最好调整外部图标文件的大小,而不是为应用程序提供额外的工作。