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

标签 java image jbutton imageicon

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

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

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

最佳答案

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

相关文章:

java - JOOQ MockDataProvider - 如何根据某些条件返回不同的模拟?

jquery - 缩放图像以适应容器,同时使用 jquery 保持纵横比

java - java中从哈希表中获取方法

java - 如何从 jButtonActionPerformed 访问另一个 jButtonActionPerformed 变量

java - 将 JButton 放在右下角

java - Java 枚举被认为是原始类型还是引用类型?

java - 为 HashMap 创建自定义迭代器

java - 如何将Java中一个字符串的单词与另一个字符串的单词进行比较并在匹配时分隔单词?

html - 为什么某些 jpeg 图片无法在旧 iOS 版本的 iPhone 中加载?

java - JFrame 未全屏显示所有图像