zoukankan      html  css  js  c++  java
  • (原)super.paintComponent解析

    在学习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进行的绘图将在有一个背景的基础下进行。
  • 相关阅读:
    蓝桥杯 历届试题 青蛙跳杯子 (BFS)
    HDOJ 1233 (克鲁斯卡尔+并查集)
    HDOJ 1198
    HDOJ 1041 (推公式,大数)水题
    单词接龙
    1284 2 3 5 7的倍数
    2020 排序相减
    isset()和empty()区别
    图像渲染
    Leetcode 328. 奇偶链表
  • 原文地址:https://www.cnblogs.com/liangjiahao/p/2744370.html
Copyright © 2011-2022 走看看