Panel.repaint();弄乱了布局 [英] Panel.repaint(); messes up layout
问题描述
JPanel Initiation
JPanel Initiation
p = new JPanel() {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
if(errors == 1)
g.drawOval(215, 50, 75, 75);
else if(errors == 2)
g.drawOval(200,200,200,200);
}
};
调用重绘的方法
static void drawHead() {
System.out.println("Head");
errors = 1;
p.removeAll();
p.revalidate();
p.repaint();
}
在重绘之前
my框架看起来像这样, http://i.imgur.com/XQlQeul.png
Before repaint
my frame looks like this, http://i.imgur.com/XQlQeul.png
之后看起来像这样, http:// i。 imgur.com/RnVuUzt.png
我认为我的 drawHead()中存在错误
方法,但我似乎无法解决问题。有谁知道发生了什么?我想要的结果将是第一张图片,但是用头
绘制。
I'm thinking there is an error in my drawHead()
method but I cannot seem to resolve the issue. Does anyone know what is going on? My desired outcome would be the first image, but with a head
drawn in.
推荐答案
您在执行任何自定义绘画之前未能先调用 super.paintComponent
打破了绘画链
You've broken the paint chain by failing to call super.paintComponent
first before you performed any custom painting
Graphics
是共享资源,在绘制周期中绘制的每个组件将共享相同的 Graphics
上下文,这意味着除非您清除它,否则以前绘制到 Graphics
上下文的任何内容都将保留。
Graphics
is shared resource, every component painted in a during a paint cycle will share the same Graphics
context, this means that whatever was previously painted to the Graphics
context will remain unless you clear it.
其中一个作业 paintComponent
是通过填充组件的背景颜色来为绘画准备 Graphics
上下文
One of the jobs of paintComponent
is to prepare the Graphics
context for painting by filling it with the background color of the component
这篇关于Panel.repaint();弄乱了布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!