Home  Contents

Java Swing first programs

In this chapter, we will program our first programs in Swing toolkit. The examples are going to be very simple. We will cover some basic functionality.

Our first example

In our first example, we will show a basic window on the screen.

package com.zetcode;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class SimpleExample extends JFrame {

    public SimpleExample() {
        
       setTitle("Simple example");
       setSize(300, 200);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);        
    }
    

    public static void main(String[] args) {
        
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                SimpleExample ex = new SimpleExample();
                ex.setVisible(true);
            }
        });
    }
}

While this code is very short, the application window can do quite a lot. It can be resized, maximised, and minimised. All the complexity that comes with it has been hidden from the application programmer.

import java.awt.EventQueue;
import javax.swing.JFrame;

Here we import Swing classes that will be used in the code example.

public class Example extends JFrame {

The Example class inherits from the JFrame component. JFrame is a toplevel container. The basic purpose of containers is to hold components of the application.

setTitle("Simple example");

Here we set the title of the window using the setTitle() method.

setSize(300, 200);

This code will resize the window to be 300px wide and 200px tall.

setLocationRelativeTo(null);

This line will center the window on the screen.

setDefaultCloseOperation(EXIT_ON_CLOSE);

This method will close the window if we click on the close button of the titlebar. By default nothing happens.

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        SimpleExample ex = new SimpleExample();
        ex.setVisible(true);
    }
});

We create an instance of our code example and make it visible on the screen. The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe. In other words, it is to prevent GUI from hanging in certain situations.

Simple example
Figure: Simple example

Quit button

In our next example, we will have a button. When we click on the button, the application terminates.

package com.zetcode;

import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

public class QuitButtonExample extends JFrame {

    public QuitButtonExample() {

        initUI();
    }

    private void initUI() {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        JButton quitButton = new JButton("Quit");

        quitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });

        gl.setAutoCreateContainerGaps(true);
        
        gl.setHorizontalGroup(gl.createSequentialGroup()
                .addComponent(quitButton)
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(quitButton)
        );
        
        pack();

        setTitle("Quit button");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                QuitButtonExample ex = new QuitButtonExample();
                ex.setVisible(true);
            }
        });
    }
}

We position a JButton on the window. We will add an action listener to this button.

public QuitButtonExample() {
    
    initUI();
}

It is a good programming practice to put the code that creates the GUI inside a specific method.

Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);

The content pane of a JFrame is an area where child components are placed. The children are organised by specialised non-visible components called layout managers. The default layout manager of a content pane is the BorderLayout manager. This manager is very simple and is useful only in certain cases. In this tutorial, we use the GroupLayout manager which is more powerful and flexible.

JButton quitButton = new JButton("Quit");

Here we create a button component.

quitButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        System.exit(0);
    }
});

We plug an action listener to the button. The listener's actionPerformed() method will be called when we perform an action on the button. In our case if we click on the button. The click will terminate the application.

gl.setAutoCreateContainerGaps(true);

The setAutoCreateContainerGaps() method creates gaps between components and the edges of the container. Space or gaps are important part of the design of each application.

gl.setHorizontalGroup(gl.createSequentialGroup()
        .addComponent(quitButton)
);

gl.setVerticalGroup(gl.createSequentialGroup()
        .addComponent(quitButton)
);

GroupLayout manager defines the layout for each dimension independently. In one step, we lay out components alongside the horizontal axis; in the other step, we lay out components along the vertical axis. In both kinds of layouts we can arrange components sequentially or in parallel. In a horizontal layout, a row of components is called a sequential group and a column of components is called a parallel group. In a vertical layout, a column of components is called a sequential group and a row of components a parallel group.

In our example we have only one button, so the layout is very simple. For each dimension, we call the addComponent() method with the button component as a parameter. (Each child component must be added for both dimensions.)

Quit button
Figure: Quit button

A tooltip

Tooltips are part of the internal application's help system. The Swing shows a small rectangular window if we hover a mouse pointer over an object that has a tooltip set.

package com.zetcode;

import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class TooltipExample extends JFrame {

    public TooltipExample() {
        
        initUI();
    }

    private void initUI() {

        JPanel pane = (JPanel) getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);
        
        pane.setToolTipText("Content pane");

        JButton btn = new JButton("Button");
        btn.setToolTipText("A button component");

        gl.setAutoCreateContainerGaps(true);
        
        gl.setHorizontalGroup(gl.createSequentialGroup()
                .addComponent(btn)
                .addGap(200)
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(btn)
                .addGap(120)
        );
        
        pack();

        setTitle("Tooltip");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                TooltipExample ex = new TooltipExample();
                ex.setVisible(true);
            }
        });
    }
}

In the example, we set the tooltip for the frame and the button.

JPanel pane = (JPanel) getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);

A content pane is an instance of the JPanel component. The getContentPane() method returns a Container type. Since setting a tooltip requires a JComponent instance, we cast the object to a JPanel.

pane.setToolTipText("Content pane");

To enable a tooltip, we call the setTooltipText() method.

gl.setHorizontalGroup(gl.createSequentialGroup()
        .addComponent(btn)
        .addGap(200)
);

gl.setVerticalGroup(gl.createSequentialGroup()
        .addComponent(btn)
        .addGap(120)
);

We call the addGap() method for horizontal and vertical dimensions. We create some space to the right and to the bottom of the button.

pack();

The pack() method automatically sizes the JFrame based on the size of its components. It takes the defined space into account too. Our window will display the button and the spaces that we have set with the addGap() method.

Tooltip
Figure: Tooltip

In this chapter, we have created some simple Java Swing programs.