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); // 绘制一个圆形
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); // 绘制一个圆形
public DrawIcon(int width, int height) { // 定义构造方法
this.width = width;
this.height = height;
}
不是出现在构造方法里面,而是在执行完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
然后多次线程调用 直到画出了圆为止(这步是我个人猜测)
不过代码确实有点奇怪,我只是把流程跟了一遍。
坐等其它更好的解释。
new的时候做了一个icon.paintIcon()的操作吧
如果你要查看是如何被调用的,可以把方法堆栈信息打印出来看看
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); //把方法堆栈信息打印出来就知道它被谁调用,什么时候被调用
}
}