paintComponent为什么会自动执行
请大家先看一段代码:
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方法明显不是该类的构造函数,为什么也可以在实例化的时候被执行呢?