Java GUI Programming
In addition to command-line and web applications, Java can also create feature-rich desktop Graphical User Interface (GUI) applications. Java provides two main GUI toolkits: Swing and JavaFX.
- AWT (Abstract Window Toolkit): Java's earliest GUI toolkit, heavily dependent on the native operating system's GUI components. It is rarely used directly now.
- Swing: Built on top of AWT, providing richer, more flexible "lightweight" components (completely drawn by Java), achieving a cross-platform consistent look and feel.
- JavaFX: As Swing's modern successor, it provides a more modern API, CSS support, 3D graphics, and richer media capabilities. Starting from JDK 11, JavaFX has been separated from the standard library and needs to be added as a separate module.
This chapter will mainly introduce the classic Swing.
Swing Basics
A Swing application typically consists of the following core parts:
-
Top-Level Containers: The starting point of a GUI, serving as the carrier for all other components.
JFrame: Represents a standard window with a title bar, border, and control buttons (minimize, maximize, close).JDialog: Represents a dialog box.JApplet: Used for Java applets running in browsers (now obsolete).
-
Intermediate Containers: Used to organize and layout other components.
JPanel: The most commonly used general-purpose container, which can be thought of as a canvas for grouping components.
-
Atomic Components: Basic controls that users interact with directly.
JButton: Button.JLabel: Text label.JTextField: Single-line text input field.JTextArea: Multi-line text area.JCheckBox: Checkbox.JRadioButton: Radio button.
Creating Your First Swing Window
Layout Managers
Layout managers are responsible for determining the size and position of components in a container. Directly setting the absolute coordinates of components (null layout) is not recommended because it cannot adapt to different screen sizes and resolutions.
FlowLayout: The default layout forJPanel. Components are arranged from left to right like flowing water, and automatically wrap when one line cannot fit.BorderLayout: The default layout forJFrame. Divides the container into five regions:NORTH,SOUTH,EAST,WEST,CENTER.GridLayout: Divides the container into a grid of equal-sized cells, with each component occupying one cell.
Event Handling
GUI applications are event-driven. When users interact with components (such as clicking a button), an event is generated. We need to write Event Listeners to respond to these events.
Example: A Simple Counter
About JavaFX
While Swing is still available and powerful, for new desktop application projects, JavaFX is Oracle's officially recommended modern alternative. It provides a richer API, supports FXML (an XML-based markup language for defining interfaces), can use CSS for styling, and better integrates modern hardware acceleration features. If you plan to dive deeper into Java GUI development, JavaFX is a direction worth investing time in.