为什么我不应该在添加组件之前调用 setVisible(true)? [英] Why shouldn't I call setVisible(true) before adding components?

查看:30
本文介绍了为什么我不应该在添加组件之前调用 setVisible(true)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个网站上多次看到它(例如这里此处) 在将组件添加到 JComponentsetVisible(true)代码>,但我没有看到解释,而且网上的资料似乎很少.

I've seen it written on this site a number of times (such as here, and here) that you mustn't call setVisible(true) before adding components to a JComponent, but I haven't seen an explanation, and information on the internet seems scarce.

为什么会这样,如果违反规则会怎样?

Why is this the case, and what happens if you break the rule?

推荐答案

如果你先调用它,你不会破坏任何东西,但如果你添加了任何东西,你可能需要再次调用它.否则 Swing 不会渲染添加的组件.您需要让 JVM 调用 JFrame 的 paint(...) 方法来呈现 JFrame 的组件,并且 setVisible(true) 将要求 JVM 执行此操作.如果您曾经在调用 setVisible(true) 之后添加组件并且没有看到这些组件,您会发现如果您重新调整 JFrame 的大小,它们将具体化".这是因为重新调整它的大小会导致操作系统要求 Swing 重新绘制 GUI,这将导致 paint(...) 被调用.

You're not breaking anything if you call it first, but you will probably then need to call it again if you've added anything. Else Swing won't render the added components. You need to have the JVM call the JFrame's paint(...) method to have the JFrame's components rendered, and setVisible(true) will ask the JVM to do just this. If you've ever add components after calling setVisible(true) and don't see the components, you'll find that they'll "materialize" if you re-size the JFrame. This is because re-sizing it causes the operating system to ask Swing to repaint the GUI, and this will result in paint(...) being called.

请注意,如果您在创建 GUI 后添加组件,则可以在其容器上调用 revalidate() 并经常调用 repaint() 来布局新组件正确,然后渲染.repaint()肯定是必要的,如果组件中的更改涉及删除,或者在之前可视化另一个组件的地方绘制组件.

Note that if you add a component after creating your GUI, you can call revalidate() and often repaint() on its container to get the new component laid out correctly and then rendered. The repaint() will definitely be necessary if the change in components involves a deletion, or a component being drawn where another component was visualized previously.

强烈推荐的书籍建议:肮脏的富客户购买盖伊和哈斯.就买吧!您不会后悔购买.

A book suggestion that I highly recommend: Filthy Rich Clients buy Guy and Haase. Just buy it! You won't regret the purchase.

这篇关于为什么我不应该在添加组件之前调用 setVisible(true)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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