JAVA中如何设置图片(图标)自适应Jlable等组件的大小
一、问题:
一个程序,组件上设置某个图片作为图标,因为的label(应该说是组件)已经设定了固定大小,
所以再打开一些大图片时,超过组件大小的部分没显示出来,而小图片又没填充完整个组件
二、解决这个问题,需要用到两个类:
java.awt.Image类
javax.swing.ImageIcon类
1.java.awt.Image是个抽象类,这个过程中用到的参数和函数如下:
(1)static int SCALE_DEFAULT 表示默认的图像缩放算法。
(2)public Image getScaledInstance(int width,int height,int hints)
创建此图像的缩放版本。返回一个新的 Image 对象,默认情况下,该对象按指定的 width 和 height 呈现图像。即使已经完全加载了初始源图像,新的 Image 对象也可以被异步加载。
如果 width 或 height 为负数,则替换该值以维持初始图像尺寸的高宽比。如果 width 和 height 都为负,则使用初始图像尺寸。
参数:
width - 将图像缩放到的宽度。
height - 将图像缩放到的高度。
hints - 指示用于图像重新取样的算法类型的标志。
返回:
图像的缩放版本。
2.javax.swing.ImageIcon类
(1)这儿用到这个构造函数:
ImageIcon(String filename) 根据指定的文件创建一个 ImageIcon对象
(2)Image getImage() 返回此图标的 Image。
(3)void setImage(Image image) 设置由此图标显示的图像。
三、关键性代码
JLabel jlb = new JLabel(); //实例化JLble int width = 50,height = 50; //这是图片和JLable的宽度和高度 ImageIcon image = new ImageIcon("image/img1.jpg");//实例化ImageIcon 对象 /*下面这句意思是:得到此图标的 Image(image.getImage()); 在此基础上创建它的缩放版本,缩放版本的宽度,高度与JLble一致(getScaledInstance(width, height,Image.SCALE_DEFAULT )) 最后该图像就设置为得到的缩放版本(image.setImage) */ image.setImage(image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT ));//可以用下面三句代码来代替 //Image img = image.getImage(); //img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT); //image.setImage(img); jlb.setIcon(image); jlb.setSize(width, height);
四、程序实例
/*java中设置图片自适应Jlable的大小*/ package test1; import javax.swing.*; import java.awt.Image; public class ImageSetTest extends JFrame { private JLabel jlb = new JLabel(); private ImageIcon image; private int width = 400, height = 400; public ImageSetTest() { this.setSize(800, 600); this.setLayout(null); image = new ImageIcon("image/img1.jpg"); // image.setImage(image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT)); Image img = image.getImage(); img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT); image.setImage(img); jlb.setIcon(image); this.add(jlb); jlb.setSize(width, height); this.setVisible(true); } public static void main(String[] args) { new ImageSetTest(); } }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。