How to Create a Java Gui with Swing (original) (raw)

In this post, we feature a comprehensive tutorial on how to create a Java Gui with Swing. There are two sets of Java APIs for graphics programming: AWT and Swing.

You can also check this tutorial in the following video:

Java Graphical User Interface Tutorial – Video

1. Java Gui tutorial with Swing – Introduction

There are two sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit) and Swing.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have become obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-Feel Support APIs. JFC was an add-on to JDK 1.1 but has been integrated into core Java since JDK 1.2.

Other than AWT/Swing Graphics APIs provided in JDK, others have also provided Graphics APIs that work with Java, such as Eclipse’s Standard Widget Toolkit (SWT) (used in Eclipse), Google Web Toolkit (GWT) (used in Android), 3D Graphics API such as Java bindings for OpenGL (JOGL) and Java3D.

2. Java GUI Creation

In this tutorial, we will learn how to create a Java GUI with Swing using Eclipse IDE.

2.1 SetUP

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.
The following steps are required to install the WindowBuilder tool.

java swing tutorial Java Gui - Installing WindowBuilder Tool

Installing WindowBuilder Tool

java swing tutorial Java Gui  - Installing WindowBuilder Tool

Installing WindowBuilder Tool

This will take some time to install the software, so you have to restart eclipse in order to see the changes.

2.2 Programming GUI with AWT

Java Graphics APIs – AWT and Swing – provides a huge set of reusable GUI components, such as button, text field, label, choice, panel and frame for building GUI applications. You can simply reuse these classes rather than re-invent the wheels. I shall start with the AWT classes before moving into Swing to give you a complete picture. I have to stress that AWT component classes are now obsoleted by Swing’s counterparts.

2.2.1 AWT Packages

AWT is huge! It consists of 12 packages (Swing is even bigger, with 18 packages as of JDK 1.8). Fortunately, only 2 packages – java.awt and java.awt.event – are commonly-used.
1. The java.awt package contains the core AWT graphics classes:

2. The java.awt.event package supports event handling:

AWT provides a platform-independent and device-independent interface to develop graphic programs that runs on all platforms, such as Windows, Mac, and Linux.

2.2.2 Containers and Components

There are two types of GUI elements:
1. Component: Components are elementary GUI entities (such as Button, Label, and TextField.)
2. Container: Containers (such as Frame and Panel) are used to hold components in a specific layout (such as flow or grid). A container can also hold sub-containers.

GUI components are also called controls (Microsoft ActiveX Control), widgets (Eclipse’s Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with (or control) the application through these components (such as button-click and text-entry).

A Frame is the top-level container of an AWT program. A Frame has a title bar (containing an icon, a title, and the minimize/maximize/close buttons), an optional menu bar and the content display area. A Panel is a rectangular area used to group related GUI components in a certain layout. In the above figure, the top-level Frame contains two Panels. There are five components: a Label (providing description), a TextField (for users to enter text), and three Buttons (for user to trigger certain programmed actions).

In a GUI program, a component must be kept in a container. You need to identify a container to hold the components. Every container has a method called add(Component c). A container (say aContainer) can invoke aContainer.add(aComponent) to add aComponent into itself. For example,

GUIProgam.java

12345 Panel panel = new Panel(); Button btn = new Button("Press"); panel.add(btn);

2.2.3 AWT Container Classes

Top-Level Containers: Frame, Dialog and Applet Each GUI program has a top-level container. The commonly-used top-level containers in AWT are Frame, Dialog and Applet:

Secondary Containers: Panel and ScrollPane
Secondary containers are placed inside a top-level container or another secondary container. AWT also provide these secondary containers:

2.2.4 AWT Component Classes

AWT provides many ready-made and reusable GUI components. The frequently-used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List, and Choice, as illustrated below. AWT GUI Component:java.awt.Label

A java.awt.Label provides a text description message. Take note that System.out.println() prints to the system console, not to the graphics screen. You could use a Label to label another component (such as text field) or provide a text description.

Check the JDK API specification for java.awt.Label.

Below is how a label will look like:

java swing tutorial Java Gui - Inserting a Label

Inserting a Label

Constructors

GUIProgam.java

1 public Label(String strLabel, int alignment);

GUIProgam.java

1 public Label(String strLabel);

GUIProgam.java

The Label class has three constructors:
1. The first constructor constructs a Label object with the given text string in the given alignment. Note that three static constants Label.LEFT, Label.RIGHT, and Label.CENTER are defined in the class for you to specify the alignment (rather than asking you to memorize arbitrary integer values).
2. The second constructor constructs a Label object with the given text string in default of left-aligned.
3. The third constructor constructs a Label object with an initially empty string. You could set the label text via the setText() method later.

GUIProgam.java

123 JLabel lblName = new JLabel("Name"); lblName.setBounds(93, 67, 46, 14); frame.getContentPane().add(lblName);

AWT GUI Component: java.awt.Button
A java.awt.Button is a GUI component that triggers a certain programmed action upon clicking.

Constructors

GUIProgam.java

1234 public Button(String buttonLabel);public Button();

The Button class has two constructors. The first constructor creates a Button object with the given label painted over the button. The second constructor creates a Button object with no label.

Here is how the button will look like:

java swing tutorial Java Gui - Insertion of a button

Insertion of a button

Clicking on a button generates an event. The code for adding a button is described below:

GUIProgam.java

12345678 JButton btnSubmit = new JButton("Submit");btnSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JOptionPane.showMessageDialog(null, "Data Submitted"); }});btnSubmit.setBounds(93, 121, 89, 23);frame.getContentPane().add(btnSubmit);

T GUI Component: java.awt.TextField
A java.awt.TextField is single-line text box for users to enter texts. (There is a multiple-line text box called TextArea.) Hitting the “ENTER” key on a TextField object triggers an action-event.

Constructors

GUIProgam.java

123456 public TextField(String strInitialText, int columns); public TextField(String strInitialText); public TextField(int columns);

Below is how a TextField will look like :

java swing tutorial - Inserting a TextField

Inserting a TextField

3. AWT Event-Handling

Now it’s time to see the AWT Event handling in this Java Gui with Swing tutorial. Java adopts the so-called “Event-Driven” (or “Event-Delegation”) programming model for event-handling, similar to most of the visual programming languages (such as Visual Basic and Delphi).

In event-driven programming, a piece of event-handling codes is executed (or called back by the graphics subsystem) when an event has been fired in response to an user input (such as clicking a mouse button or hitting the ENTER key). This is unlike the procedural model, where codes are executed in a sequential manner.

The AWT’s event-handling classes are kept in package java.awt.event.

Three objects are involved in the event-handling: a source, listener(s) and an event object.

The source object (such as Button and Textfield) interacts with the user. Upon triggered, it creates an event object. This event object will be messaged to all the registered listener object(s), and an appropriate event-handler method of the listener(s) is called-back to provide the response. In other words, triggering a source fires an event to all its listener(s), and invoke an appropriate handler of the listener(s).

The sequence of steps is illustrated above:

How the source and listener understand each other? The answer is via an agreed-upon interface. For example, if a source is capable of firing an event called XxxEvent (e.g., MouseEvent) involving various operational modes (e.g., mouse-clicked, mouse-entered, mouse-exited, mouse-pressed, and mouse-released). Firstly, we need to declare an interface called XxxListener (e.g., MouseListener) containing the names of the handler methods. Recall that an interface contains only abstract methods without implementation

Secondly, all the listeners interested in the XxxEvent must implement the XxxListener interface. That is, the listeners must provide their own implementations (i.e., programmed responses) to all the abstract methods declared in the XxxListener interface. In this way, the listenser(s) can response to these events appropriately.

Thirdly, in the source, we need to maintain a list of listener object(s), and define two methods: addXxxListener() and removeXxxListener() to add and remove a listener from this list.

Take note that all the listener(s) interested in the XxxEvent must implement the XxxListener interface. That is, they are sub-type of the XxxListener. Hence, they can be upcasted to XxxListener and passed as the argument of the above methods.

In summary, we identify the source, the event-listener interface, and the listener object. The listener must implement the event-listener interface. The source object then registers listener object via the addXxxListener() method.

4. Java Swing class Hierarchy

Java Swing Container classes are used to build screens that have components. The user interface typically needs one container. Java Swing has three types of Container classes. The container classes will have Window and JComponent.The Frame class is a subclass of Window. The Panel class which is a subclass of JComponent is used to compose the window components. The JFrame which is a subclass of Frame class is used for a window which has title and images. The Dialog class which is a subclass of Window is similar to a Popup window.

Java Gui - Swing Hierarchy

Java Swing Hierarchy

5. Advanced Swing Example

In this section of the Java Gui with Swing article, we will look at a WordFrequency Application tutorial. The application will have a Login screen and WordFrequencyCalculator screen. The login screen code is shown below in the WordFrequencyManager.

WordFrequencyManager

import javax.swing.;
import java.awt.event.
;

/**

}

Login screen will have username and password fields. Password will be JPasswordField type. Username will be JTextField. The login screen UI will be as in the attached screenshot.

java swing tutorial - Login Screen

Login Screen

User inputs the username and password for submission. The user will be navigated to the next window. The login screen with filled-in fields will be as shown in the screenshot below.

java swing tutorial - Login Screen with Input

Login Screen with Input

WordFrequencyWindow will have a JTextArea and Jbutton fields. WordFrequencyWindow class source code is as shown below.

WordFrequencyWindow

/**

* / import javax.swing.;
import java.awt.event.; /*

}

The word Frequency window, when launched in eclipse will be as shown in the screenshot below.

java swing tutorial - Word Frequency

Word Frequency Calculator Window

User inputs the text area with a text which has words. The calculator window after input is filled looks as shown in the screenshot below:

Word Frequency Calculator Window Input

The user clicks on the calculate button to find the words and characters on the screen. The output screen after the calculation is shown in the screenshot below.

Word Frequency Window Output

6. Summary

In this tutorial, we saw Java Swing which is a lightweight GUI toolkit that includes a rich set of widgets.

We used Eclipse IDE to create a GUI, we learned what is the AWT Event-Handling and what is the Java Swing class hierarchy. Finally, we saw an advanced Swing Example creating a WordFrequency Application.

7. Download The Source Code

That was a tutorial about how to create a Java Gui with Swing.

Last updated on Mar. 09th, 2020