Add components directly to JFrame, or put them inside a JPanel?

依然范特西╮ 提交于 2019-12-02 10:36:33

问题


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.


回答1:


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.

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.

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.




回答2:


As you had correctly mentioned JFrame is regular container with all features including Layout Manager. Unless you plan to use the same view somewhere else then there is no reason to have additional wrapper.



来源:https://stackoverflow.com/questions/29604302/add-components-directly-to-jframe-or-put-them-inside-a-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!