JPanel 图形清除和重绘? [英] JPanel Graphics clearing and repainting?

查看:52
本文介绍了JPanel 图形清除和重绘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 paintComponent() 函数的 JPanel.我将调用它一次,然后当用户单击不同的 JButton 时,我将设置一些标志并希望再次调用此函数,因为在设置标志后它会做一些略有不同的事情.

I have a JPanel with a paintComponent() function. I'll call it once, then when the user clicks a different JButton, I'll set some flag and want to call this function again as it will do something slightly different after the flag is set.

所以这就是我想知道的:如何清除 paintComponent 中的现有内容?要重绘,我是否只需再次调用 paintComponent ?

So here's what I'm wondering: how do I clear the existing stuff from paintComponent? And to redraw, do I just call paintComponent again?

目前我正在尝试以下方法:

Currently I'm trying the following:

flag2 = true;
repaint(); //I expect (want) paintComponent to be called again

在绘制组件中,我做的事情是:

In paint component, I do stuff like:

if (flag2==true) {
    g.drawRect(...);
} else {
    g.drawLine(...);
}

但是通过测试,我所做的似乎有问题.

But through testing it seems like there is something wrong with what I'm doing.

感谢您的帮助.

推荐答案

当你改变面板的属性时,你需要调用:

When you change a property of the panel then you need to invoke:

panel.repaint();

导致组件被重新绘制.

那么paintComponent()方法中的第一条语句应该是:

Then the first statement in the paintComponent() method should be:

super.paintComponent(g);

这将绘制背景,以便您现在可以进行自定义绘制.

This will paint the background so you can now do your custom painting.

如果您需要更多帮助,请发布说明问题的 SSCCE.

If you need more help then post your SSCCE that demonstrates the problem.

这篇关于JPanel 图形清除和重绘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆