10. Graphical User Interfaces

Chapter 1010 2

Help Make These Materials Better!

I am actively working to complete and revise this eBook and the accompanying videos. Please consider using the following link to provide feedback and notify me of typos, mistakes, and suggestions for either the eBook or videos:

What’s the Point?

  • Identify the characteristics of a GUI

  • Understand the role of the Swing library

  • Create a GUI using Swing widgets

  • Create event handlers that interact with widgets

Source code examples from this chapter and associated videos are available on GitHub.


10.1. Graphical User Interfaces

Until now, we’ve been creating console applications, in which the entire user interface is text-based. Though many utility applications are text-based, those are generally used by "power users," software developers, and system administrators. End users are used to applications that rely graphical elements to interact with the user. This is called a graphical user interface, which is abbreviated as GUI and pronounced "gooey."

GUIs on desktop and laptop computers have elements like windows, buttons, text fields, and checkboxes, and the user interacts using a mouse or touchpad. These GUI elements are called widgets or controls. Mobile applications have similar widgets, but they are designed for touchscreens and are generally more simplified than desktop applications.

Time To Watch!

Intro to GUIs

10.2. The Swing Library

The code required to create and display a functioning GUI is complex and far beyond our current skills, but we can use pre-built GUI widgets written by other developers. These are typically bundled into libraries, or frameworks, that we can use in our own programs. The two most common GUI frameworks for Java are called Swing and JavaFX; we’ll use Swing in this course because it’s a little simpler for beginners and does not require any additional installations.

JavaFX is newer and more powerful than Swing, but it’s also more complex and has a steeper learning curve. The concepts learned in Swing will transfer to JavaFX, so learning Swing is a great place to start. Plus, we don’t need to install anything extra to use it.

To use Swing classes, we simply need to add an import statement at the top of our Java file:

[source,java]import javax.swing.*;

We’ll begin by instantiating a JFrame object, which is the main window of our application. We can use setters on the JFrame object to set attributes like the title and size of the window; we’ll also want to set the attribute that determines what happens when the user closes the window. We can then add other widgets to the frame, like buttons, text fields, and labels. Finally, we’ll set the frame to be visible, which will cause the window to appear on the screen.

Example 10.1 - A simple "Hello World!" GUI using Swing
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import javax.swing.*;

public class BasicGUI {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Hello, World!");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel lblHello = new JLabel("It's so gooey!");
        frame.add(lblHello);
        frame.setVisible(true);
    }

}

This code creates a window with the title "Hello, World!" and a label that says "It’s so gooey!".

The JFrame.EXIT_ON_CLOSE attribute tells the program to exit when the user closes the window. If this attribute is not set, the program will continue running in the background after the window is closed. There are a few other options for this attribute, but EXIT_ON_CLOSE is the most common.
Basic GUI
Figure 10.1 - Screenshot of BasicGUI.java in action on macOS.

As you can see, the code to create a simple GUI is a little more complex than the single println() statement of an equivalent console application, which is why we’ve waited until now to learn it.

Time To Watch!

Intro to Swing in Java

Files from video:

10.3. Event-Driven Programming with Swing

A GUI application offers a lot more flexibility than a console application, since the user can interact with the program in many ways. In a console application, the program runs from top to bottom, and the user can only interact by typing text. In a GUI application, the user can click buttons, type in text fields, and select items from drop-down lists. This means that the program must be able to respond to these events; we call this event-driven programming, and it is a key concept in GUI programming.

In Swing, we can add event listeners to widgets, which are objects that respond to events. For example, we can add an event listener to a button that will run a method when the button is clicked. The method that runs in response to an event is called an event handler. Once we’ve added an event listener to a widget, the event handler is like any other method in our program, and we can write it to do whatever we want.

Time To Watch!

Swing Event Handling

Files from video:

Note: there is no starter code for this video.

10.4. Processing User Input with Swing

Once we’ve learned how to work with widgets and add event listeners, we can put everything together to create a GUI application that gets input from the user, performs actions or calculations with that data, and displays the results.

Time To Watch!

Calculations in Swing

Files from video:

10.5. Widgets

Using JLabel and JTextField, we’ve been about to create GUI programs that function much like console applications, but that doesn’t really take advantage of the power of GUIs. A well-designed GUI application utilizes specialized widgets that are designed for specific types of user input and output.

Here are some common widgets and their purposes:

JLabel

Displays text or an image.

JTextField

Allows the user to type in a single line of text.

JTextArea

Allows the user to type in multiple lines of text.

JButton

A clickable button that can run a method when clicked.

JCheckBox

A checkbox that can be checked or unchecked.

JRadioButton

A radio button that can be selected or deselected, and can be grouped with other radio buttons to limit the user to selecting only one.

JComboBox

A drop-down list that allows the user to select one item from a list.

There are many more widgets in the Swing framework, but these will cover most of what you’ll need for basic GUI applications. There is a great deal of documentation available online for the Swing framework, so you can always look up how to use a specific widget.

Use widgets as they are intended, even if they are able to be used in other ways, such as displaying output in a text field. Users are accustomed to certain behaviors from widgets, and using them in unexpected ways can make the application harder to use.

10.5.1. Widget Naming Conventions

When naming widgets, it’s a good idea to use a consistent naming convention that makes it clear what type of widget it is. There are a variety of conventions for naming widgets, but two are most common:

  • Prefix the name to identify the widget type, like lbl for a label, txt for a text field, or btn for a button.

  • Append the type of widget to the end of the name, like helloLabel, nameTextField, or submitButton.

I use the prefix method in my code, mostly because I’m used to that from C# programming (where that’s the preferred style), but you can use either approach on your assignments. The most important thing is to be consistent in your naming so that anyone reading your code can easily understand what each widget is for.

Time To Watch!

More Swing Widgets

Files from video:

10.6. GUI Layouts

As we add more widgets to our GUI, we’ll need to consider how they are arranged on the screen. While we can set the position of each widget manually, this is tedious and doesn’t work well when the window is resized. Instead, we should use layout managers, which are objects that arrange widgets in a specific way and respond to window and screen sizes in predictable ways. Think of a layout manager as a set of rules that determine how widgets are arranged in a window.

The Swing framework is itself built on top of another framework called the Abstract Window Toolkit, or AWT. Swing hides most of that from us by implementing classes that extend the AWT classes. For example, the JLabel class is a Swing widget that extends the Label class from AWT. So we don’t directly use AWT very often, but layout managers are an exception. Layout managers are part of AWT, so we’ll have to import them from the java.awt package:

[source,java]import java.awt.*;

There are several layout managers available in AWT, each with its own strengths and weaknesses. The most common layout managers are:

FlowLayout

Widgets are arranged in a single row or column, and wrap to the next row or column when the window is resized.

GridLayout

Widgets are arranged in a grid, with a specified number of rows and columns.

BorderLayout

Widgets are arranged in five regions: north, south, east, west, and center.

To create more complex layouts, we can nest layout managers, which means that we can put a layout manager inside another layout manager.

There are tools that allow us to create GUIs visually, by dragging and dropping widgets onto a window, and then generating the code that will produce the GUI. But our goal is to learn how layout managers work, so we’ll be creating our GUIs by writing the code ourselves. For GUI designs that don’t have to be turned into an obnoxious professor for a grade, you’re welcome to take advantage of these tools.

Time To Watch!

Swing Layouts

Files from video:


Check Yourself Before You Wreck Yourself (on the assignments)

Chapter Review Questions

  1. What is a Graphical User Interface (GUI) and why is it important for end users?

  2. Explain the role of the Swing library in Java and why it is preferred for beginners over JavaFX.

  3. Describe the process of creating a simple GUI using Swing, including the main components involved.

  4. What is event-driven programming in the context of GUIs, and how does it differ from console-based programming?

Sample answers provided in the Liner Notes.