- Java code
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 drawMe
display()是由其它类不停调用的,从打印结果里能看出,display里的repaint第一次调用的时候连续重绘了两次,以后就正常了,这是为什么呢??
------解决方案--------------------
代码放全一点看看
------解决方案--------------------
这个正常,因为paintComponent方法不光可被repaint触发,其他如初次布局、resize、窗口移动等因素都会触发paintComponent方法执行。
------解决方案--------------------
正如2楼说的,Swing会在很多时候,自动repaint的
楼主这里的现象是由于在componentShown事件时,
自动repaint引起的
看源码中的两段吧:
- Java code
public void componentShown(ComponentEvent e) { if (shouldShow()) { synchronized (getTreeLock()) { if (peer != null) { peer.show(); } } } }
------解决方案--------------------
只要窗体显示、布局、位置稍有改变都会触发...