问题
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