gpt4 book ai didi

java - JButton 更改图像并保持大小

转载 作者:行者123 更新时间:2023-11-29 05:52:42 25 4
gpt4 key购买 nike

实际上,我已经知道如何更改按钮中的图像,但问题在于尺寸。

我更改了新图标,但我想保留大小,但此更改请对此提出一些建议。

我尝试在更改图像之前获取按钮的尺寸以进行设置,但尺寸不会缓存,并且在视觉上不会改变。

最佳答案

那是因为按钮使用了一个固定大小的图标。如果您想在 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;
}

但是,最好改为调整外部图标文件的大小,而不是给您的应用程序增加额外的工作量。

关于java - JButton 更改图像并保持大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com