import java.awt.*;import javax.swing.*;public class DrawIcon implements Icon { // 实现Icon接口
private int width; // 声明图标的宽
private int height; // 声明图标的长

public int getIconHeight() { // 实现getIconHeight()方法
return this.height;
}

public int getIconWidth() { // 实现getIconWidth()方法
return this.width;
}

public DrawIcon(int width, int height) { // 定义构造方法
this.width = width;
this.height = height;
}

// 实现paintIcon()方法
public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
arg1.fillOval(x, y, width, height); // 绘制一个圆形

}

public static void main(String[] args) {
DrawIcon icon = new DrawIcon(30, 30);
// 创建一个标签,并设置标签上的文字在标签正中间
JLabel j = new JLabel("测试", icon, SwingConstants.CENTER);
JFrame jf = new JFrame(); // 创建一个JFrame窗口
Container c = jf.getContentPane();
c.add(j);
jf.setSize(100,100);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}这个方法没有被任何对象调用怎么会画出圆形,也就是它怎么被执行的public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
arg1.fillOval(x, y, width, height); // 绘制一个圆形

解决方案 »

  1.   

    是不是在构造方法默认调用了呢
     public DrawIcon(int width, int height) { // 定义构造方法
            this.width = width;
            this.height = height;
        }
      

  2.   

    我看了一下代码的流程
    不是出现在构造方法里面,而是在执行完Main方法最后一步的时候,程序并没有结束
    它在结束的时候调用了线程 Tread exit()line; 结果是:Source not found  然后跳过线程以后就进去到了
        public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
            arg1.fillOval(x, y, width, height); // 绘制一个圆形
            
        }执行这不和Component arg0, Graphics arg1这2个参数有关。但是第一次绘制圆形没成功,原因是进入MetalLableUI  结果又是:Source not found
    然后多次线程调用 直到画出了圆为止(这步是我个人猜测)
    不过代码确实有点奇怪,我只是把流程跟了一遍。
    坐等其它更好的解释。
      

  3.   

    JLabel j=new JLabel("test",icon,SwingConstants.CENTER);这里调用了icon,icon重绘时会调用paintIcon
      

  4.   

    我来扩展下楼上所说的。因为你implement 了Icon这个接口,Icon里的paintIcon方法就是你要完成的接口。当你设定了Icon在JLabel里,这个方法会自动被调用。所以也就会出现个圆形了。
      

  5.   

     JLabel j = new JLabel("测试", icon, SwingConstants.CENTER);
     new的时候做了一个icon.paintIcon()的操作吧
      

  6.   

    这是swing或awt框架内部调用的,不需要显式调用
    如果你要查看是如何被调用的,可以把方法堆栈信息打印出来看看
    public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
            arg1.fillOval(x, y, width, height); // 绘制一个圆形
             for (StackTraceElement se : Thread.currentThread().getStackTrace()) {
                System.out.println(se); //把方法堆栈信息打印出来就知道它被谁调用,什么时候被调用
            }
        }