9. Graphical User Interfaces
Chapter 1001 2
What’s the Point?
* *
Source code examples from this chapter and associated videos are available on GitHub.
9.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.
9.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. |
To use Swing classes, we simply need to add an import
statement at the top of our Java file:
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.
What’s the Point?
* *
Source code examples from this chapter and associated videos are available on GitHub.
Check Yourself Before You Wreck Yourself (on the assignments)
Chapter Review Questions
Sample answers provided in the Liner Notes.