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
import javax.swing.JFrame;
public class FirstWindow {
public static void main(String[] args) {
// 1. Create a JFrame object
JFrame frame = new JFrame("My First GUI Window");
// 2. Set the default operation when the window is closed
// EXIT_ON_CLOSE means exit the application when the window is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 3. Set the window size (unit: pixels)
frame.setSize(400, 300);
// 4. Make the window visible
frame.setVisible(true);
}
}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
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CounterApp {
private static int count = 0;
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Counter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// Create a panel
JPanel panel = new JPanel();
frame.add(panel);
// Create components
JLabel label = new JLabel("Click count: 0");
JButton button = new JButton("Click me!");
// Add components to the panel
panel.add(label);
panel.add(button);
// Add event listener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Code to execute when the event occurs
count++;
label.setText("Click count: " + count);
}
});
frame.setVisible(true);
}
}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.