Please enable JavaScript to use CodeHS

Basic Java Swing Layouts

In this tutorial, students will learn the basics of Java Swing and how to set up a page and add a simple layout. It is a good place to start if students do not have previous Java Swing experience.

By David Burnham

Introduction


There are several different ways to implement graphics in Java, but perhaps the most common method is to use the Java Swing library. Swing was developed to provide a better interface compared to its predecessor, Java AWT, however as you will see, we still borrow a couple of pieces from the AWT library (mainly colors) as we implement Java Swing.

This tutorial will cover the basic program and layout setup for Java Swing. Subsequent tutorials will look at various components of Java Swing, including user events.


Basic Program Structure


While you may be used to starting your program and putting most of your code in the main method, Java Swing programs structure their code a little differently. You will see a few different styles for program structure, but in this tutorial, we will use the format suggested by Oracle on the Java document section.

The basic program layout uses a runnable to call a function that implements the Java Swing graphics.


public class Example{
    
    public static void createAndShowGUI(){
        
        // Write your Swing program here
    }
    
    // Basic script to kickofff Swing program
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


In the example above, you can see how the main method only uses basic boilerplate code. All of the code that you will write for the program will then go into the createAndShowGUI method.


Basic Swing Layout

Swing graphics use a multilayered approach. The base layer is a Java frame (JFrame) object. The frame contains different layers on which we can add content. In this tutorial, we are going to work with the content layer.

By default, the content layer uses a BorderLayout format, but others such as BoxLayout, FlowLayout, etc. are available. The BorderLayout is a very versatile layout that has a single top and bottom section and then three sections in the middle.

Each of these sections can then have various components, such as panels, buttons, text fields, etc.

Take a few minutes to examine the program below. The program creates a basic frame and then adds 5 different color panels to the content layer. Each panel is a different color so that you can see how a BorderLayout is arranged.

Notice the flow of the program above. The program first creates the JFrame object. It then create JPanel objects, set the color, and then adds them to the frame's content pane. To add them, you specify which part of the BorderLayer to add them to.

Finally, the program pack's the frame and shows it. Packing the frame is the step where Java resizes the components based on their preferred size and any conflicts. In this case, the panel components don't specify a size, so Java just fills in with a large center panel.


Sizing the Panels


In the example below, the program now sets a preferred size for each of the panels. Notice that it is a preferred size. Components need to fit within the frame or other containers they may be in, so it is possible that the packing step changes the actual size of a component. For example, if the top and bottom panels are different sizes, one will have to be resized to make the frame square.

Feel free to play around with the sizes to see the effect. You can also remove one of the sections to see the impact that has.

Adding components to your page


As mentioned above, Swing graphics use a layered approach. So far, our example starts with a JFrame base and JPanels have been added to each section of the base content pane.

Additional components can then be added on top of those. In the example below, the program is going to add a JLabel with the text "Hello World" centered. Just like the content pane, the JPanels have a default BorderLayout, so the program specifies adding the label into the center section.

Other Layouts


While the BorderLayout is versatile, there are other layouts that you may want to consider. Each of these has a unique style and way to implement. In the example below, we will be implementing a FlowLayout which essentially adds elements in a linear order and then moves on to the next row once it reaches the edge.

Notice that the example below adds a JPanel into the content pane, and then updates the layout to the FlowLayout. It then adds different color JPanel objects into the FlowLayout. Try changing the sizes of the panels to see the impact.

To see more layout types, you can find examples on the Oracle Java Docs site.