如何调整 JLabel ImageIcon 的大小? [英] How to resize JLabel ImageIcon?

查看:44
本文介绍了如何调整 JLabel ImageIcon 的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个具有以下布局的 Java Swing 应用程序 (MigLayout):>

I'm making a Java Swing application that has the following layout (MigLayout):

[icon][icon][icon][....]
where icon = jlabel and the user can add more icons

当用户添加或删除图标时,其他图标应该缩小或增大.

When the user adds or removes icons, the others should shrink or grow.

我的问题非常简单:我有一个 JLabel,其中包含一个 ImageIcon;如何调整此图标的大小?

My question is really straightforward: I have a JLabel which contains an ImageIcon; how can I resize this icon?

推荐答案

调整图标大小并不简单.您需要使用 Java 的 2D 图形来缩放图像.第一个参数是一个 Image 类,您可以从 ImageIcon 类中轻松获取它.您可以使用 ImageIcon 类来加载您的图像文件,然后只需调用 getter 方法来获取图像.

Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

这篇关于如何调整 JLabel ImageIcon 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆