将组件直接添加到JFrame,还是将它们放在JPanel中? [英] Add components directly to JFrame, or put them inside a JPanel?

查看:127
本文介绍了将组件直接添加到JFrame,还是将它们放在JPanel中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Java GUI,我有一个一般性问题.如果我有几个要添加到JFrame的组件,我应该将它们直接放在JFrame中,还是将它们添加到JPanel,然后将面板添加到框架中?如果最好先将组件添加到JPanel,为什么?我通常这样做,然后我了解到我不知道为什么/如果这是更可选的,然后直接添加到框架中. JFrame还具有布局管理器,因此可以将它们放置在正确的位置.

I have a general question regarding java GUI. If I have several components that I want to add to a JFrame, should i put them directly inside the JFrame, or add them to a JPanel, and then add the panel to the frame? If adding the components to a JPanel first is the best, why? I usually do this, then I understood that I have no idea why/if this is more optional then adding directly to the frame. JFrame also have layout managers, so it's possible to get them in the correct position.

推荐答案

将组件添加到框架时,将组件添加到框架的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.

这篇关于将组件直接添加到JFrame,还是将它们放在JPanel中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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