请帮我看一段代码 百思不解

卑微的去爱你 2011-08-06 09:17:18
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); // 绘制一个圆形
...全文
231 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
卑微的去爱你 2011-08-07
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 qybao 的回复:]

这是swing或awt框架内部调用的,不需要显式调用
如果你要查看是如何被调用的,可以把方法堆栈信息打印出来看看
Java code
public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
arg1.fillOval(x, y, width, height); // 绘制一个圆形
……
[/Quote]
谢谢拉 ,我突然想到 ,可以查看类的源代码
qybao 2011-08-07
  • 打赏
  • 举报
回复
这是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); //把方法堆栈信息打印出来就知道它被谁调用,什么时候被调用
}
}
jamespengo 2011-08-06
  • 打赏
  • 举报
回复
JLabel j = new JLabel("测试", icon, SwingConstants.CENTER);
new的时候做了一个icon.paintIcon()的操作吧
zwb_1988 2011-08-06
  • 打赏
  • 举报
回复
我来扩展下楼上所说的。

因为你implement 了Icon这个接口,Icon里的paintIcon方法就是你要完成的接口。

当你设定了Icon在JLabel里,这个方法会自动被调用。所以也就会出现个圆形了。
xybcrab 2011-08-06
  • 打赏
  • 举报
回复
JLabel j=new JLabel("test",icon,SwingConstants.CENTER);

这里调用了icon,icon重绘时会调用paintIcon
feifeikub 2011-08-06
  • 打赏
  • 举报
回复
我看了一下代码的流程
不是出现在构造方法里面,而是在执行完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
然后多次线程调用 直到画出了圆为止(这步是我个人猜测)
不过代码确实有点奇怪,我只是把流程跟了一遍。
坐等其它更好的解释。
卑微的去爱你 2011-08-06
  • 打赏
  • 举报
回复
是不是在构造方法默认调用了呢
 public DrawIcon(int width, int height) { // 定义构造方法
this.width = width;
this.height = height;
}

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧