奇怪的paintComponent()

  paintComponent定义在JComponent中,这个类是所有非窗口Swing组件的超类,只要窗口需要重新绘图,事件处理器就会通告组件,从而引发执行所有组件的paintComponent方法。一定不要自己调用paintComponent方法。--摘自《Java核心技术》 

以下是部份源码:

protected void paintComponent(Graphics g) {
           
//注意这里
// super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        
//draw all rectangles
        for (Rectangle2D rect : squares) {
            g2.draw(rect);
        }

}

 
public void add(Point2D p) {
        
double x = p.getX();
        
double y = p.getY();

        current 
= new Rectangle2D.Double(
                x 
- SIDELENGTH / 2,
                y 
- SIDELENGTH / 2,
                SIDELENGTH,
                SIDELENGTH);
        squares.add(current);
        repaint();
}

  
public void remove(Rectangle2D p) {
        
if (p == null{
            
return;
        }

        
if (p == current) {
            current 
= null;
        }

        squares.remove(p);
        repaint();
    }

    
private static final int SIDELENGTH = 10;
    
private ArrayList<Rectangle2D> squares;
private Rectangle2D current;

当鼠标单击panel的时候,就会调用add方法,Panel面板上立刻出现了一个小方块。当鼠标在小方块上双击的时候,就会调用remove方法,但是Panel面板上的小方块并不能立刻消失,必须将整个面板最小化,或者改变面板大小的时候,面板上的小方块才会消失。也就是说,remove方法中repaint()并没有立刻生效。

然而把 super.paintComponent(g)前的//去掉之后不管是addremove中调用repaint()都立刻生效。

JComponent中的paintComponent方法:

protected void paintComponent(Graphics g) {
        
if (ui != null{
            Graphics scratchGraphics 
= (g == null? null : g.create();
            
try {
                ui.update(scratchGraphics, 
this);
            }

            
finally {
                scratchGraphics.dispose();
            }

        }

}

   
protected transient ComponentUI ui;

是什么原因导致执行了上面一段代码之后,面板就可以立即更新了呢?难道跟dispose释放资源有关?



好好活着,因为我们会死的很久!

posted on 2008-08-14 17:18 RaviLi 阅读(3826) 评论(3)  编辑  收藏 所属分类: Java相关

评论

# re: 奇怪的paintComponent() 2008-08-14 19:44 Matthew Chen  回复  更多评论   

remove(Rectangle2D r)的参数是如何获得的?是通过点击生成的吧,这个能够和List里面的匹配吗?用==看起来怪怪的,是不是该用equals,代码不够全,看不透。

# re: 奇怪的paintComponent() 2008-08-14 21:19 zht  回复  更多评论   

super.paintComponent(g);的作用就是清除以前绘制的内容,实际上就是使用backgroundcolor,fill一下整个区域,如果不调用这个的话自然不会清除。
而当最小化又最大化的时候,我理解的是,会根据层次结构由paintmanger负责重画所有的界面,就相当于整个界面都是新的,自然会清除掉以前绘制的内容

# re: 奇怪的paintComponent() 2008-08-15 22:46 千里冰封  回复  更多评论   

你把它改成paint就知道了

只有注册用户登录后才能发表评论。


网站导航: