JAVA Swing Application Example

Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way.

1. Introduction

Swing API is set of extensible GUI Components to ease developer’s life to create JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criteria.

2. JAVA Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

2.1 MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

Every user interface considers the following three main aspects:

2.2 Swing Features

2.3 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

2.4 Class and description

2.4 SWING UI Elements

3. Creating Swing Application

We will learn Swing basics through this example i.e, HelloWorld.java

code for HelloWorld.java

HelloWorld.java

import javax.swing.*;        
public class HelloWorldSwing {
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add the ubiquitous "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

This is one of the simplest Swing applications you can write. It doesn’t do much, but the code demonstrates the basic code in every Swing program:

1.Import the pertinent packages.
2.Set up a top-level container.
3.Display the container.
4.Be thread-safe.

The first line imports the main Swing package:

import javax.swing.*;

This is the only package that HelloWorldSwing needs. However, most Swing programs also need to import two AWT packages:

import java.awt.*;
import java.awt.event.*;

These packages are required because Swing components use the AWT infrastructure, including the AWT event model. The event model governs how a component reacts to events such as button clicks and mouse motion. You’ll learn more about events in the upcoming section Handling Events (in the Creating a GUI with JFC/Swing trail).

Every program with a Swing GUI must have at least one top-level Swing container. A top-level Swing container provides the support Swing components need for painting and event handling. There are three commonly used top-level Swing containers: JFrame, JDialog, and (for applets) JApplet. Each JFrame object implements a single main window, and each JDialog implements a secondary window (a window dependent on another window). Each JApplet object implements an applet’s display area within a browser window. (JApplet is covered in How to Make Applets(in the Creating a GUI with JFC/Swing trail).)

The HelloWorldSwing example has only one top-level container, a JFrame. Imple­mented as an instance of the JFrame class, a frame is a window that, by default, has dec­orations such as a border, a title, and buttons for iconifying and closing the window. Applications with a GUI typically use at least one frame.

Here is the code that sets up and shows the frame:

HelloWorld.java

JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HelloWorldSwing");

With the exception of top-level containers, such as JFrame, all Swing components descend from the JComponent class. HelloWorldSwing uses a JComponent descendant called JLabel, which displays the text Hello World. These two lines of code construct and then add the JLabel component to the frame:

HelloWorld.java

JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);

Note that the label is added to the frame’s content pane instead of to the frame itself. Every top-level container has a content pane that contains, directly or indirectly, all the visible components (except for menus and window decorations) in the top-level container.

To make the program exit when the Close button close is clicked, we include this code:

HelloWorld.java

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The Output of the code when executed will look like the one below.

JAVA Swing Example

4. Download The Source Code

This was an example of creation of JAVA Swing.

Download
You can download the full source code of this example here: HelloWorld
Exit mobile version