(原)super.paintComponent解析

在学习java的画图功能时候,经常会看到super.paintComponent,书上说一定要有而且必须是在第一句,不然就会出问题!可恨的是书上没有解析这是为什么。下面简单的解析一下这个语句的作用。
 

首先我们要知道GUI组件(如JPanel,JButton等)本身并没有paintComponent的方法,它的paintComponent是JComponent继承下来的。
  然后我们来看看JComponent的paintComponent
   protected void paintComponent(Graphics g) {
        if (ui != null) {
            Graphics scratchGraphics = SwingGraphics.createSwingGraphics(g);
            try {
                ui.update(scratchGraphics, this);
            }
            finally {
                scratchGraphics.dispose();
            }
        }
}
createSwingGraphics的有什么用呢?  只是用于创建一个新的画图对象而与
public static Graphics createSwingGraphics(Graphics g) {
        if (g == null) {
            Thread.dumpStack();
            return null;
        }
        return g.create();
}
那update呢?  明显是用于画出组件的背景色
public void update(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        g.setColor(c.getBackground());
        g.fillRect(0, 0, c.getWidth(),c.getHeight());
    }
    paint(g, c);
}
最后就用dispose把画图的对象占用的资源释放掉!
综合以上,我们发现paintComponenet的作用是给组件画上背景色。如果不调用此方法,我们之前对组件设置的背景色等属性将不会被展现。如果此 方法在子类的实现中最先被调用,背景就处于最底下的一层,子类其他利用g进行的绘图将在有一个背景的基础下进行。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值