这是绘制椭圆的简单示例。
public class SwingPainter extends JFrame{
public SwingPainter() {
super("Swing Painter");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(new MySwingComponent());
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
new SwingPainter();
}
class MySwingComponent extends JComponent {
public void paintComponent(Graphics g) {
System.out.println("paintComponent");
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(10, 10, 50, 50);
}
@Override
protected void paintBorder(Graphics g) {
System.out.println("Paint border");
super.paintBorder(g);
}
@Override
protected void paintChildren(Graphics g) {
System.out.println("Paint children");
super.paintChildren(g);
}
}
}
但在 Debug模式下或在绘制之前向控制台添加一些信息(如示例),您可以看到 swing 绘制组件两次。
paintComponent
Paint border
Paint children
paintComponent
Paint border
Paint children
我不明白为什么会这样,但我认为它会影响复杂 GUI 中的性能。
最佳答案
文章Painting in AWT and Swing: Additional Paint Properties: Opacity说明了原因:“不透明属性允许 Swing 的绘制系统检测特定组件上的重绘请求是否需要底层祖先的额外重绘。”因为您扩展了 JComponent
,所以 opaque
属性默认为 false,无法进行优化。将属性设置为 true
以查看差异,以及不遵守该属性的工件。可以找到相关示例here和 here .
关于java - 为什么 swing 会绘制两次简单的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11966980/