1
其实,我已经知道如何更改按钮中的图像,但问题与大小有关。JButton改变图像并保持大小
我改变了新的图标,但我想保留大小,但这个改变请与此一些建议。
我试图在更改图像设置它之前获取按钮的尺寸,但尺寸不会缓存,并且它不会在视觉上发生变化。
其实,我已经知道如何更改按钮中的图像,但问题与大小有关。JButton改变图像并保持大小
我改变了新的图标,但我想保留大小,但这个改变请与此一些建议。
我试图在更改图像设置它之前获取按钮的尺寸,但尺寸不会缓存,并且它不会在视觉上发生变化。
这是因为按钮使用了一个固定大小的图标。如果你想做到这一点在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;
}
但是,它可能会更好,而不是调整外部图标文件,并没有给出额外的工作,以您的应用程序。
您是否需要将图像缩放以适应按钮,或调整按钮大小?最好的建议是不做,而是分发一组相同大小的图标。顺便说一句 - 图标的纵横比是否相同? –