有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JButton更改图像并保持大小

事实上,我已经知道如何更改按钮中的图像,但问题在于大小

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

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


共 (1) 个答案

  1. # 1 楼答案

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

    不过,最好是调整外部图标文件的大小,而不是让应用程序承担额外的工作