paintComponent为什么会自动执行

zhangzhexin_81 2006-03-15 05:57:44
请大家先看一段代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Font2Panel extends JPanel
{
public void paintComponent(Graphics g)
{
String MyQuote="Happiness is an attitude.";
Font f=new Font("Times New Roman",Font.BOLD+Font.ITALIC,24);
FontMetrics fm=getFontMetrics(f);
g.setFont(f);
int x,y;
x=(getSize().width-fm.stringWidth(MyQuote))/2;
y=(getSize().height-fm.getHeight())/2;
g.drawString(MyQuote,x,y);
}
}
class FontsFrames extends JFrame
{
public FontsFrames()
{
setTitle("test");
setSize(400,250);
Container con=getContentPane();
con.add(new Font2Panel());//请注意这里,实例化了一个Font2Panel类
addWindowListener(new myWinClo());
}
class myWinClo extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
public class Font2Demo {
public static void main(String[] args)
{
new FontsFrames().show();
}

}
请注意上面注释的地方,当一旦实例化了Font2Panel类以后,该类的方法:paintComponent就自动执行了,这是为什么呢?书上不是说实例化一个类的时候只是执行该类的构造函数啊,paintComponent方法明显不是该类的构造函数,为什么也可以在实例化的时候被执行呢?
...全文
256 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
supersunyi 2006-03-15
  • 打赏
  • 举报
回复
paintComponent是jcomponent的方法,你现在是重载了父类的方法,你把paintComponent换个名字就不会运行了,还有paintComponent运行是jcomponent决定的,不管任何类,只要你继承jcomponent,就会执行paintComponent方法[绘制组件]。。。。不知道说什么了,呵呵

62,624

社区成员

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

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