(原)super.paintComponent解析

来源:互联网 发布:东村明子 知乎 编辑:程序博客网 时间:2024/04/30 16:42

在学习java的画图功能时候,经常会看到super.paintComponent,书上说一定要有而且必须是在第一句,不然就会出问题!可恨的是书上没有解析这是为什么。下面简单的解析一下这个语句的作用。
 

首先我们要知道GUI组件(如JPanel,JButton等)本身并没有paintComponent的方法,它的paintComponent是JComponent继承下来的。
  然后我们来看看JComponent的paintComponent
  protected void paintComponent(Graphics g) {
        if (ui != null) {
            Graphics scratchGraphics = SwingGraphics.createSwingGraphics(g);
            try {
                ui.update(scratchGraphics, this);
            }
            finally {
                scratchGraphics.dispose();
            }
        }
}
createSwingGraphics的有什么用呢?  只是用于创建一个新的画图对象而与
public static Graphics createSwingGraphics(Graphics g) {
        if (g == null) {
            Thread.dumpStack();
            return null;
        }
        return g.create();
}
那update呢?  明显是用于画出组件的背景色
public void update(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        g.setColor(c.getBackground());
        g.fillRect(0, 0, c.getWidth(),c.getHeight());
    }
    paint(g, c);
}
最后就用dispose把画图的对象占用的资源释放掉!
综合以上,我们发现paintComponenet的作用是给组件画上背景色。如果不调用此方法,我们之前对组件设置的背景色等属性将不会被展现。如果此方法在子类的实现中最先被调用,背景就处于最底下的一层,子类其他利用g进行的绘图将在有一个背景的基础下进行。
0 0