简体   繁体   English

调整JFrame大小后会发生什么?

[英]What happens when a JFrame is resized?

I am curious as to what happens exactly in Java when a JFrame is resized. 我很好奇当JFrame调整大小时,Java中究竟会发生什么。

I am asking this because of an issue I am having with adding a component to my bigCOntainer (of type JPanel) inside the JFrame. 我问这个是因为我在JFrame中向我的bigCOntainer(类型为JPanel)添加一个组件时遇到了一个问题。 I want to add something when the user performs a certain action but the component doesn't become visibly added until the JFrame is resized somehow. 我希望在用户执行某个操作时添加一些内容,但是在JFrame以某种方式调整大小之前,该组件不会被明显添加。

I discovered this when I was doing some experimenting trying to get the new component to show up; 当我做一些尝试让新组件出现时,我发现了这个; I called myJFrame.pack(). 我调用了myJFrame.pack()。 As a secondary question I would like to know what pack() does, both generally and specific to resizing. 作为第二个问题,我想知道pack()的作用,通常和特定于调整大小。 The Java Documentation makes it sound like it will resize every component to its preferred size. Java文档使得它将每个组件的大小调整为其首选大小。 My solution, if I decide to use pack() in my implementation to display new components is to always set a preferred size. 我的解决方案,如果我决定在我的实现中使用pack()来显示新组件,则总是设置首选大小。 Can anyone attest to this being an accepted programming practice? 任何人都可以证明这是一个公认的编程实践吗? It sure seems like a good idea. 这看起来确实是一个好主意。

I also tried repaint() to get the new component to show up but that did not work. 我也试过repaint()来显示新的组件但是没有用。

You need to call revalidate() and then repaint() on the container that gets components added or removed during run-time. 您需要调用revalidate()然后在运行时添加或删除组件的容器上repaint()

revalidate() tells the container's layout managers to re-layout the components it contains, and this is what is missing from your code. revalidate()告诉容器的布局管理器重新布局它包含的组件,这是代码中缺少的。 Without this request, the layouts don't change, and you don't see the changes until you re-size the GUI, which pretty much does the same thing. 如果没有此请求,布局不会更改,并且在重新调整GUI大小之前,您不会看到更改,这几乎完全相同。

Note that if you're adding components to the GUI on start-up, then the solution is to call pack() and setVisible(true) to the top-level container only after all components have been added. 请注意,如果您在启动时向GUI添加组件,则解决方案是仅添加所有组件后将 pack()setVisible(true)调用到顶级容器。

For specifics about say what pack() does, do what we all do -- read the source code. 有关说什么pack()功能,做我们所做的事情 - 阅读源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM