paint和paintComponent方法的关系

关键词:swing,paint,paintComponent,paintBorder

paint :绘制容器。
paintComponents : 绘制此容器中的每个组件。


由此不难看出,二者就是房子与家具的关系。

但是该类中并不包含paintBorder方法,由此我想,该方法应该是位于扩展包中,很幸运,在javax.Swing包中的JComponent类中,找到了paint,paintComponent和paintBorder三个方法,我想这应该就是小朱宇要问的,查看API,有如下解释:

paint :由 Swing 调用,以绘制组件。此方法实际上将绘制工作委托给三个受保护的方法:paintComponent、paintBorder 和 paintChildren。按列出的顺序调用这些方法,以确保子组件出现在组件本身的顶部。子类可以始终重写此方法。只想特殊化 UI(外观)委托的 paint 方法的子类只需重写 paintComponent。

paintComponent :如果 UI 委托为非 null,则调用该 UI 委托的 paint 方法。向该委托传递 Graphics 对象的副本,以保护其余的 paint 代码免遭不可取消的更改

paintBorder :绘制组件的边框。
paintChildren :绘制此组件的子组件。


由此可以看出,在Swing 中,组件绘制 paint() 方法会依次调用 paintComponent(),paintBorder(),paintChildren() 三个方法。根据方法名就可以看出,paintComponent() 绘制组件本身,paintBorder() 绘制组件的边框,paintChildren() 绘制组件的子组件,所以Swing 编程时,如果继承 JComponent 或者其子类需要重绘的话,只要覆写 paintComponent() 而不是 paint(),方法 paintBorder(),paintChildren() 一般默认即可。

如下面的程序我们写了一个类ZPanle继承自JPanel,我们只要重写protected void paintComponent(Graphics g) 就可以得到不同的显示效果。
package com.zakisoft.frame02;  

  

import java.awt.Graphics;  

import java.awt.Image;  

  

import javax.swing.Icon;  

import javax.swing.ImageIcon;  

import javax.swing.JPanel;  

  

public class ZPanel extends JPanel {  

  

    private static final long serialVersionUID = 6702278957072713279L;  

    private Icon wallpaper;  

  

    public ZPanel() {  

        System.out.println("f:ZPanel()");  

    }  

  

    protected void paintComponent(Graphics g) {  

        if (null != wallpaper) {  

            processBackground(g);  

        }  

        System.out.println("f:paintComponent(Graphics g)");  

    }  

  

    public void setBackground(Icon wallpaper) {  

        this.wallpaper = wallpaper;  

        this.repaint();  

    }  

  

    private void processBackground(Graphics g) {  

        ImageIcon icon = (ImageIcon) wallpaper;  

        Image image = icon.getImage();  

        int cw = getWidth();  

        int ch = getHeight();  

        int iw = image.getWidth(this);  

        int ih = image.getHeight(this);  

        int x = 0;  

        int y = 0;  

        while (y <= ch) {  

            g.drawImage(image, x, y, this);  

            x += iw;  

            if (x >= cw) {  

                x = 0;  

                y += ih;  

            }  

        }  

    }  
} 


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值