Swing_paint和paintComponent方法…

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) 就可以得到不同的显示效果。 
Java代码
  收藏代码
  1. package com.zakisoft.frame02;  
  2.   
  3. import java.awt.Graphics;  
  4. import java.awt.Image;  
  5.   
  6. import javax.swing.Icon;  
  7. import javax.swing.ImageIcon;  
  8. import javax.swing.JPanel;  
  9.   
  10. public class ZPanel extends JPanel  
  11.   
  12.     private static final long serialVersionUID 6702278957072713279L;  
  13.     private Icon wallpaper;  
  14.   
  15.     public ZPanel()  
  16.         System.out.println("f:ZPanel()");  
  17.      
  18.   
  19.     protected void paintComponent(Graphics g)  
  20.         if (null != wallpaper)  
  21.             processBackground(g);  
  22.          
  23.         System.out.println("f:paintComponent(Graphics g)");  
  24.      
  25.   
  26.     public void setBackground(Icon wallpaper)  
  27.         this.wallpaper wallpaper;  
  28.         this.repaint();  
  29.      
  30.   
  31.     private void processBackground(Graphics g)  
  32.         ImageIcon icon (ImageIcon) wallpaper;  
  33.         Image image icon.getImage();  
  34.         int cw getWidth();  
  35.         int ch getHeight();  
  36.         int iw image.getWidth(this);  
  37.         int ih image.getHeight(this);  
  38.         int 0 
  39.         int 0 
  40.         while (y <= ch)  
  41.             g.drawImage(image, x, y, this);  
  42.             += iw;  
  43.             if (x >= cw)  
  44.                 0 
  45.                 += ih;  
  46.              
  47.          
  48.      
  49.  


文章地址:  http://javapub.iteye.com/blog/763849
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值