JFrame in Java with Examples


JFrame is the standard window for graphical user interface programming with Swing. It takes all the other containers and controls and combines them into one interface.

A frame has the following structure:


The last level should represent the entire frame, which is made up of the layers above it.

The basis is the RootPane. As the name already implies, this represents the beginning of a frame and the associated container hierarchy. The RootPane contains the so-called LayeredPane (from layer = plane). The children of a LayeredPane are associated with a layer, which can also move depending on usage. A LayeredPane in turn has a so-called ContentPane (from English content = content), which contains the actual control elements, as well as a menu bar ( JMenuBar ). However, the menu bar is optional. The top layer is the so-called GlassPane.This is like a transparent pane directly above the ContentPane. All panes together form the frame.

Typically, only the ContentPane, its controls, and its optional menu bar are accessed.

Now let’s look at an example of how to create a simple frame:

We create a JFrame object using the new operator and pass the constructor our title. We then set the width is 300 and the height is 200 pixels using the setSize method. Finally, we use the setVisible method to display the frame.

After running the source code above, you should get the following screen:


We have now created a window, but we don’t yet know how to fill this with elements. We want to use a very simple example to demonstrate how you can add elements without much effort and without a special layout:

The add method adds new components to our frame. We now extend the above example:

Now our example window contains a JLabel component (label). As you can see, here we just added an import statement for our JLabel and called the add method, in which we passed an object of the JLabel class as a parameter. We passed the desired text for the JLabel component to the constructor of the JLabel class.

When executing the modified source code, we now get the following picture:


In this way, any control elements can be added to our interface using the add method. We will show how each control works and how it can be added to a frame in the later articles.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button