一、Icon: Icon位于javax.swing包中,它是一个接口 public interface Icon,介绍为:一个小的固定大小的图片 ,通常用于装饰组件 有三个方法: int getIconHeight(); int getIconWidth(); void paintIcon(Component c,Graphics g,int x,int y); Icon木有用过,提到它是因为ImageIcon实现了Icon接口(ImageIcon还实现了Accessible, Serializable接口,不过这里不具体说明了) 二、ImageIcon: ImageIcon位于javax.swing包中。可以根据Image绘制Icon(这句话很关键),可以使用MediaTracker预 载图像(Image也可以) 构造方法不少,举几个常用的:
ImageIcon(String name); ImageIcon(URL url); 主要方法:
int getIconWidth(); void paintIcon(Component c,Graphics g,int x,int y); image getImage();
要给控件加图片的话,可以很轻松地 JLabel label = new JLabel(new ImageIcon("a.png"));搞定(这个是用来与后面的Image的加图片对比 的); 三、Image
获取图像。 它的主要方法是:Image getScaledInstance(int width,int height,int hints) hints为:指示用于图像重新取样的算法类型的标志,具体可用的几个参数如下: SCALE_AREA_AVERAGING 使用 Area Averaging 图像缩放算法。 。 我们生成Image对象时需要借助于Toolkit类的getImage方法,而生成Toolkit对象有两种方法,一是借助 于Component类的getToolkit()方法,一是借助于Toolkit的静态方法getDefaultToolkit(); 所以呢,如果要使用Image类来为组件添加图标的话有两种方法 一种是: //该类继承了Component或其子类
JButton jb = new JButton(new ImageIcon(image)); 另一种: Image image = new Toolkit.getDefaultToolkit().getImage("a.png"); JButton jb = new JButton(new ImageIcon(image)); 那么,为什么不直接用ImageIcon呢?前者不是更简单吗? 是的,前者更简单。但是Image可以对图像进行加工(比如调节大小使图像变灰等等)。 举一个例子,使用一个大图片来设置为小按钮的背景图: [java] view plaincopyprint?import javax.swing.*; 我想看了上面的内容,关于Image和ImageIcon的区别您已经有所体会了吧。 关于他们的互相的转换,也希望大家能够记住,使用起来会相当顺手: Image的图给ImageIcon Image image
2.imageIcon.getImage(image);
ImageIcon的图给Image 1.image = imageIcon.getImage();
|
|