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

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

问题描述

我已经多次在此网站上看到它(例如此处,并且其他)在将组件添加到a之前,不得调用 setVisible(true) JComponent ,但我没有看到解释,互联网上的信息似乎很少。

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?

推荐答案

如果你先打电话,你不会破坏任何东西,但是如果你添加了任何东西,你可能需要再次调用它。 Else 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.

高度 推荐的图书建议:肮脏的富客户买Guy和Haase。买吧!你不会后悔购买。

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天全站免登陆