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第一次调用的时候连续重绘了两次,以后就正常了,这是为什么呢??
楼主这里的现象是由于在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();
}
}
}