From the course: Learn Java with Swing

Top-level containers - Java Tutorial

From the course: Learn Java with Swing

Start my 1-month free trial

Top-level containers

- [Instructor] To understand Swing, we need to talk briefly about top-level containers. These are four of the top-level containers in Swing. We have JFrame, JWindow, JDialog, and JApplet. For this series, I will be only using the JFrame container. Each of these containers relies on the JRootPane, because instead of adding components directly to the container, you add them to a part of the RootPane. The RootPane actually then manages them all internally. So, the JRootPane acts as a container delegate for the top-level Swing containers. When we're creating our GUI, in order for something to appear in the window to the user, that GUI component must be added to part of the containment hierarchy. Each graphical user interface component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and added to the second. Every top-level container has a content pane, such as a panel, that contains the visible components in that top-level container's graphical user interface. Let's look at an example of a Swing application. In this example, I would have my JFrame, which, again, is my top-level container. In order to add components to my window, I first need to add another frame, such as a JPanel. So, I can add my JPanel to my JFrame. From there, I can start adding components to my panel. Here, I just have a few components that indicate they could be text fields, they could be radio buttons, they could be labels. So, remember, you can't add components directly to JFrame. First, you have to add a panel, then you can add the components to the panel, and the panel to the frame.

Contents