在Swing中通过Icon接口来创建图标,可以在创建时 指定图标的大小、颜色等特性。

必须实现Icon接口中的三个方法:

1、 public int getIconHeight();    //设置图标的长

2、 public int getIconWidth();    //设置图标的宽

3、 public void paintIcon(Component arg0, Graphics arg1, int arg2, int arg3) ;    //实现在指定位置坐标画图

也可以用图片的方式来代替图标,简单明了,而且可以对图片进行诸多设置,如:大小、位置等等。

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;

public class t2 implements Icon{

private static final JFrame jframe = new JFrame();//创建一个窗体

private static final Box base = Box.createVerticalBox();//设置盒子,用来存放 jlabel 标签
private static final Box box1 = Box.createHorizontalBox();
private static final Box box2 = Box.createHorizontalBox();

private int height;//图标的高
private int width;//图标的宽

public static void main(String[] args) {
// TODO Auto-generated method stub

//方法一:自己绘制图形
t2 icon = new t2(20,20);

//方法二:自己添加图标
ImageIcon image = new ImageIcon("E:\\下载\\图标.jpg");//设置图片的来源路径(图片的URL)
image.setImage(image.getImage().getScaledInstance(100, 100, 100));//设置图片大小

jframe.setTitle("实现Icon组件窗体");//设置窗体标题
jframe.setBounds(600, 600, 600, 600);//设置窗体大小
jframe.setBackground(Color.WHITE);//设置窗体背景颜色
jframe.setVisible(true);//设置窗体可见性

JLabel jlabel = new JLabel("标签内容",icon, SwingConstants.CENTER);//创建一个标签用于存放图标icon
JLabel jlabel2 = new JLabel();

//jlabel.setHorizontalAlignment(SwingConstants.CENTER);//设置标签内容水平对齐
//jlabel.setVerticalAlignment(SwingConstants.CENTER);//设置标签内容垂直对齐

jlabel2.setIcon(image);//将图片添加到标签中

box1.add(jlabel);
box2.add(jlabel2);
base.add(box1);
base.add(box2);

jframe.add(base);

jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗体默认关闭方式

}

public t2(int weight, int height) { //定义 t2 的构造方法

this.width = weight;
this.height = height;
}

@Override
public int getIconHeight() {
// TODO Auto-generated method stub
return this.height;
}

@Override
public int getIconWidth() {
// TODO Auto-generated method stub
return this.width;
}

@Override
public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
// TODO Auto-generated method stub
arg1.fillOval(x, y, width, height);//绘制一个圆形
arg1.setColor(Color.GREEN);///设置圆形的颜色为绿色


}

}

代码运行效果图:

Java Icon图标的使用_ico