在JPanel上画图时为何paint()方法会被多次调用?

tripofdream tripofdream 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码如下:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

public class InfoPanel extends JPanel
{
private Image img = Toolkit.getDefaultToolkit().getImage(
InfoPanel.class.getResource("about.jpg"));
private int count = 0;

public InfoPanel()
{

}

public void paint(Graphics g){
super.paint(g);
g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this);
count ++;
System.out.println(count);
}

public static void main(String[] args){
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.setSize(400,200);
InfoPanel info = new InfoPanel();
f.getContentPane().add(info);
f.setVisible(true);
}
}

运行结果:
1
2
3
4
......
301
302
说明paint方法被多次调用,为什么?这样图片需要很长时间才能显示,怎样让图片立即显示?
...全文
评论 13
收藏 已收藏
分享
返回顶部
tripofdream
Java SE 62,621 成员 307,251 内容