Java Swing revalidate()vs repaint() [英] Java Swing revalidate() vs repaint()

查看:107
本文介绍了Java Swing revalidate()vs repaint()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在整理一个Swing应用程序,我常常想要替换JPanel的内容。为此,我正在调用 removeAll(),然后添加我的新内容,然后调用 revalidate()

I'm putting together a Swing application where I often want to replace the contents of a JPanel. To do this, I'm calling removeAll(), then adding my new content, then calling revalidate().

但是我发现旧内容实际上仍然可见(虽然被新内容遮挡了)。如果我在 revalidate()之外添加对 repaint()的调用,它将按预期工作。

However I'm finding that the old content is still actually visible (though obscured by the the new content). If I add a call to repaint() in addition to revalidate(), it works as expected.

我确信在其他情况下我只是打电话给 revalidate()就足够了。

I'm sure on other occasions I've experienced that just calling revalidate() is enough.

基本上我的问题是 - 我是否需要调用这两个函数?如果不需要,我应该何时调用它们?

So basically my question is - should I need to call both functions and if not, when should I call each of them?

推荐答案

您需要调用 repaint() revalidate()。前者告诉Swing窗口区域是脏的(这是擦除由 removeAll()删除的旧子项的图像所必需的);后者告诉布局管理器重新计算布局(添加组件时这是必要的)。这应该导致面板的 children 重新绘制,但可能不会导致面板本身这样做(参见这个用于重绘触发器列表。)

You need to call repaint() and revalidate(). The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by removeAll()); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause children of the panel to repaint, but may not cause the panel itself to do so (see this for the list of repaint triggers).

更一般的说明:而不是重复使用原始面板,我建议建立一个新面板并将其交换到父面板。

On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.

这篇关于Java Swing revalidate()vs repaint()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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