/*1.由Component.java源代码中可以看见其中的paint()方法体是空的,在Container中重写了该方法,其子类Window等也重写了该方法2.由JComponent.java源代码中可以看见其中的paint()方法中调用paintComponent, paintChildren, paintBorder等方法;所以该类中的paint方法会影响子组件的绘制, 而paintComponent方法只会影响该组件本身3.paint方法 和 paintComponent方法都是对一个组件进行渲染的(组件创建并显示之后),并不是产生和显示该组件的!4.swing 组件和 awt组件 paint方法的不同:awt组件的paint方法有自动刷新背景颜色的功能, 而swing组件一定要调用super.paint()
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BkGnd extends Frame{public BkGnd(){setTitle("更换背景!");setSize(new Dimension(600, 600));setLayout(new FlowLayout());myPanelOne panel = new myPanelOne();panel.setBackground(Color.yellow);panel.setPreferredSize(new Dimension(500, 500));myPanelTwo pl = new myPanelTwo();pl.setPreferredSize(new Dimension(400, 400));pl.setBackground(Color.blue);panel.add(pl);add(panel);addWindowListener(new MyClosingListener());}public static void main(String args[]){BkGnd myFrame = new BkGnd();myFrame.setVisible(true);}
}/*
//第一种情况: 如果没有super.paint(g);则该面板上的组件将不能正常显示
//如果加上super.paint(g);那么首先通过该方法将该面板上的组件显示出来,然后在执行super.paint(g);下面的绘图语句。会导致将该面板上的组件覆盖
//父类的paint方法来负责调用paintComponent, paintChildren, paintBorder, update方法
class myPanelOne extends JPanel{public void paint(Graphics g){super.paint(g);g.drawImage(new ImageIcon("zjy1.jpg").getImage(), 0, 0, 400, 400, this);}
}class myPanelTwo extends JPanel{public void paintComponent(Graphics g){super.paintComponent(g);g.drawImage(new ImageIcon("zjy1.jpg").getImage(), 0, 0, 200, 200, this);}
}*//*
//第二种就可以的到正常预想的结果
class myPanelOne extends JPanel{public void paintComponent(Graphics g){super.paintComponent(g);//用于绘制自身面板的背景g.drawImage(new ImageIcon("zjy1.jpg").getImage(), 0, 0, 400, 400, this);}
}class myPanelTwo extends JPanel{public void paintComponent(Graphics g){super.paintComponent(g);g.drawImage(new ImageIcon("zjy1.jpg").getImage(), 0, 0, 200, 200, this);}
}*///重写Component类中的paint()方法的子类,super.paint(g) 不会影响其子组件。
//第三种的效果等同于第二种的效果(正常的预想的结果)
class myPanelOne extends Panel{public void paint(Graphics g){//super.paint(g);//加和不加都一样g.drawImage(new ImageIcon("zjy1.jpg").getImage(), 0, 0, 400, 400, this);}
}class myPanelTwo extends Panel{public void paint(Graphics g){g.drawImage(new ImageIcon("zjy1.jpg").getImage(), 0, 0, 200, 200, this);}
}/*
*/class MyClosingListener extends WindowAdapter{public void windowClosing(WindowEvent e){System.exit(0);}
}