一:JLabel
新建MyIcon类实现Icon接口,再用此类实例化对象绘画一个圆,添加到JLabel中
package n1;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class MyICon implements Icon{
private int width;
private int height;
public MyICon(int width,int height){
this.width=width;
this.height=height;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillOval(x, y, width, height);
//用Graphics对象来填充椭圆
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
public static void main(String[] args) {
MyICon icon=new MyICon(15, 15);
JLabel label=new JLabel("你好",icon,SwingConstants.CENTER);
JFrame jf=new JFrame("窗口");
Container container=jf.getContentPane();
container.setBackground(Color.white);
container.add(label);
jf.setVisible(true);
jf.setSize(300, 200);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}