为什么摆得出简单的组件两次? [英] Why does swing draw simple component twice?
问题描述
下面是绘制一个椭圆的简单例子。
Here is simple example of drawing an oval.
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);
}
}
}
但在调试模式或添加一些信息图形(如实例)前控制台,您可以看到,摆绘制组件的两倍。
But in debug mode or adding some info to console before drawing (as in example), you can see that swing draws components twice.
的paintComponent
paintComponent
油漆边界
儿童漆
的paintComponent
paintComponent
油漆边界
儿童漆
我不明白为什么会发生,但我认为它可以在一个困难的GUI影响性能。
I cannot understand why it happens, but I think it can affect performance in a difficult GUI.
推荐答案
这篇文章的 绘画在AWT和Swing:其他的涂料性能:不透明度的表明了原因:不透明属性允许Swing的涂料体系来检测特定组件上重绘请求是否需要额外的重绘底层的祖先与否。因为你延长的JComponent
的不透明
属性默认为false,和优化是不可能的。设置属性真正
看出差别,以及来自不履行该属性的神器。相关的例子可以在这里找到 和的这里。
The article Painting in AWT and Swing: Additional Paint Properties: Opacity suggests why: "The opaque property allows Swing's paint system to detect whether a repaint request on a particular component will require the additional repainting of underlying ancestors or not." Because you extend JComponent
, the opaque
property is false by default, and optimization is not possible. Set the property true
to see the difference, as well as the artifact from not honoring the property. Related examples may be found here and here.
这篇关于为什么摆得出简单的组件两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!