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) 就可以得到不同的显示效果。
文章地址: http://javapub.iteye.com/blog/763849
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