int i; //记录重绘次数
          public void display(Shape shape,Ground ground){
System.out.println("GamePanel's display begin");
this.shape = shape;
this.ground = ground;
repaint();
System.out.println("GamePanel's display  end");
}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub

if(shape !=null && ground != null){

System.out.println(i++);
shape.drawMe(); //此方法会打印Shape's drawMe
ground.drawMe(); //此方法会打印Ground's drawMe
}
}
打印结果:
GamePanel's display begin //第一次调用display
GamePanel's display begin
0
Shape's drawMe
Ground's drawMe
1
Shape's drawMe
Ground's drawMe
GamePanel's display begin //第二次调用display
GamePanel's display  end
2
Shape's drawMe
Ground's drawMe
GamePanel's display begin //第三次调用display
GamePanel's display  end
3
Shape's drawMe
Ground's drawMedisplay()是由其它类不停调用的,从打印结果里能看出,display里的repaint第一次调用的时候连续重绘了两次,以后就正常了,这是为什么呢??

解决方案 »

  1.   

    这个正常,因为paintComponent方法不光可被repaint触发,其他如初次布局、resize、窗口移动等因素都会触发paintComponent方法执行。
      

  2.   

    正如2楼说的,Swing会在很多时候,自动repaint的
    楼主这里的现象是由于在componentShown事件时,
    自动repaint引起的
    看源码中的两段吧:        public void componentShown(ComponentEvent e) {
                if (shouldShow()) {
                    synchronized (getTreeLock()) {
                        if (peer != null) {
                            peer.show();
                        }
                    }
                }
            }
        public void show() {
            if (!visible) {
                synchronized (getTreeLock()) {
                    visible = true;
                    mixOnShowing();
                    ComponentPeer peer = this.peer;
                    if (peer != null) {
                        peer.show();
                        createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
                                              this, parent,
                                              HierarchyEvent.SHOWING_CHANGED,
                                              Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
                        if (peer instanceof LightweightPeer) {
                            repaint();
                        }
                        updateCursorImmediately();
                    }                if (componentListener != null ||
                        (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
                        Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
                        ComponentEvent e = new ComponentEvent(this,
                                                              ComponentEvent.COMPONENT_SHOWN);
                        Toolkit.getEventQueue().postEvent(e);
                    }
                }
                Container parent = this.parent;
                if (parent != null) {
                    parent.invalidate();
                }
            }
        }