如下的一小段代码:...
class MyPanel extends JPanel{
    public void paintComponent(Graphics g)
    {
         super.paintComponent(g); 
         g.setColor(Color.red);
         g.fillRect(10,10,80,30);    }
}
...
我想问其中的super.paintComponent方法有什么用,怎么还看到有的paintComponent中没有用调用super.paintComponent呢,那么什么情况可以去掉,什么时候必须有这行呢?

解决方案 »

  1.   

    不调用super.paintComponent(g)的话,rePaint()的时候就会把你写的paintComponent中的内容绘制上去。如果你调用super.paintComponent(g),那么就会把整个组件彻底清空,然后依次再绘制。所以你要是增量绘制就别写super.paintComponent(g),如果是新图就写上super.paintComponent(g)。你要是要了解细节,其实只要去看看JPanel的源代码就知道了。
      

  2.   

    非常感谢cweijiaweil,基本明白了
    再问下,怎么增量绘制呢,比如JPanel上原来有一些图形,后来想再增加其他图形是要调用JPanel的paintComponent(g)方法吗?
      

  3.   

    1楼的概念是正确的. 不过小小的纠正一下:所以你要是增量绘制就别写super.paintComponent(g),如果是新图就写上super.paintComponent(g)。好象是刚好弄反了哦, 如果增量绘制, 就要加上super.paintComponent(g)... 呵呵
    第2个问题, 我想是需要重新继承JPanel重写paintComponent, 然后替换已有的JPanel
      

  4.   


    增量绘制一定要替换掉原来的MyJPanel吗,不能在原来的MyJPanel基础增加绘制一些图形吗,
    如果替换,那么super.paintComponent(g)岂不是没用了吗
      

  5.   

    运行下这段程序就明白了.import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class ButtonDemo extends JPanel implements ActionListener{
        JButton b1,b2;
        String message="请点击按钮";
        int row=50,col=50;    public ButtonDemo(){
            //按钮1
            b1=new JButton("First Button");
            b1.setActionCommand("first");
            b1.addActionListener(this);
            //按钮2
            b2=new JButton("Second Button");
            b2.setActionCommand("second");
            b2.addActionListener(this);        add(b1);
            add(b2);
        }    public void actionPerformed(ActionEvent e){
            if(e.getActionCommand().equals("first")){
                message="第一个按钮被按下!";
                row=50;
                col=50;
            }else if(e.getActionCommand().equals("second")){
                message="第二个按钮被按下!";
                row=50;
                col=150;
            }
            repaint();   //注意这一行
        }    public void paintComponent(Graphics g){
            super.paintComponent(g);  //注意这一行
            g.drawString(message, col, row);
        }    public static void main(String args[]){
            JFrame jf=new JFrame("按钮测试!");
            jf.getContentPane().add(new ButtonDemo());
            jf.setSize(300,200);
            jf.setVisible(true);
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }paintComponent方法在JPanel初始化时执行一次。使用repaint方法会导致调用paintComponent方法.
    如果把super.paintComponent(g)这行注释掉,会发现点击按钮时以前输出的字符串仍然存在,没有被清除掉.