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 x = 0;  
  39.         int y = 0;  
  40.         while (y <= ch) {  
  41.             g.drawImage(image, x, y, this);  
  42.             x += iw;  
  43.             if (x >= cw) {  
  44.                 x = 0;  
  45.                 y += ih;  
  46.             }  
  47.         }  
  48.     }  
  49. }  


文章地址: http://javapub.iteye.com/blog/763849
發佈了76 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章