且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将组件直接添加到JFrame,还是将它们放在JPanel中?

更新时间:2023-12-05 18:24:10

将组件添加到框架时,将组件添加到框架的content pane.内容窗格是一个JPanel.内容窗格的默认布局是BorderLayout.

When you add components to the frame you add the components to the content pane of the frame. The content pane is a JPanel. The default layout for the content pane is a BorderLayout.

将组件直接添加到框架时,实际上是在将组件添加到面板.因此,您具有面板的所有布局功能.因此,实际上,向框架添加组件或使用自己的面板作为框架的内容窗格没有什么区别.

When you add components directly to frame you actually are adding the components to a panel. So you have all the layout features of the panel. So in reality there is no difference for adding components to the frame or be using your own panel as the content pane of the frame.

您真正需要确定的是,是否确实出于任何原因需要访问内容窗格?查看Swing教程中使用***容器的部分. 了解更多信息.本教程对此主题进行了一些思考.

What you really need to decide is do you really need to access the content pane for any reason? Take a look at the section from the Swing tutorial on Using Top Level Containers for more information. The tutorial gives some thought on this subject.

我不确定为什么您需要替换内容窗格的组件.如果您阅读了该论坛上的帖子,则建议始终使用CardLayout交换面板,因此您永远不会直接处理内容窗格.

I'm not sure why you would need to replace components of the content pane. If you read the posting on this forum the suggestion is to always use a CardLayout to swap panels, so you would never deal directly with the content pane.