paint和paintComponent方法的關係
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;
- }
- }
- }
- }
文章地址: http://javapub.iteye.com/blog/763849