AWT 和 Swing 中组件的绘制方式不同,绘制方法的实现也有区别。
AWT 中组件重绘时先调用 update(Graphics g) 清除以前绘制的,再调用 paint() 方法里进行绘制,所以在 AWT 组件里重绘时,只要简单的覆写 paint() 方法就可以了。
而在Swing 中,组件绘制 paint() 方法会依次调用 paintComponent(),paintBorder(),paintChildren() 三个方法。根据方法名就可以看出,paintComponent() 绘制组件本身,paintBorder() 绘制组件的边框,paintChildren() 绘制组件的子组件,所以Swing 编程时,如果继承 JComponent 或者其子类需要重绘的话,只要覆写 paintComponent() 而不是 paint(),方法 paintBorder(),paintChildren() 一般默认即可。
|