GUI Programming (Swing)
Swing is Java's GUI toolkit, which has existed since Java 1.1. Although older than JavaFX, Swing is still relevant for legacy desktop applications and internal tools. Swing uses the MVC (Model-View-Controller) model and supports a customizable Look and Feel.
JFrame is the main window. JPanel is a container for combining components. Main components: JLabel (text), JTextField (text input), JButton (button), JComboBox (dropdown), JTable (data table), and JOptionPane (dialogs).
Event-driven programming — every user interaction (click, input) invokes event handler methods via an ActionListener. Layout managers (BorderLayout, GridLayout, FlowLayout, GridBagLayout) control the placement of components.
Main Swing Components:
| Component | Use |
|---|---|
JFrame |
Main window |
JPanel |
Component container |
JLabel |
Text/image |
JTextField |
Single-line text input |
JTextArea |
Multi-line text input |
JButton |
Button |
JTable |
Data table |
JOptionPane |
Popup dialog |
Code Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingExample extends JFrame {
JTextField nameField, emailField;
JTextArea outputArea;
public SwingExample() {
// Window setup
setTitle("Registration Form");
setSize(400, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
// Form panel
JPanel formPanel = new JPanel(new GridLayout(3, 2, 5, 5));
formPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
formPanel.add(new JLabel("Name:"));
nameField = new JTextField();
formPanel.add(nameField);
formPanel.add(new JLabel("Email:"));
emailField = new JTextField();
formPanel.add(emailField);
JButton submitBtn = new JButton("Register");
formPanel.add(submitBtn);
JButton clearBtn = new JButton("Clear");
formPanel.add(clearBtn);
// Output area
outputArea = new JTextArea(5, 30);
outputArea.setEditable(false);
outputArea.setBorder(BorderFactory.createTitledBorder("Result"));
// Add to the frame
add(formPanel, BorderLayout.NORTH);
add(new JScrollPane(outputArea), BorderLayout.CENTER);
// Event handling
submitBtn.addActionListener(e -> {
String name = nameField.getText().trim();
String email = emailField.getText().trim();
if (name.isEmpty() || email.isEmpty()) {
JOptionPane.showMessageDialog(this,
"All fields are required!", "Error",
JOptionPane.WARNING_MESSAGE);
return;
}
outputArea.append("Registered: " + name + " (" + email + ")\n");
nameField.setText("");
emailField.setText("");
});
clearBtn.addActionListener(e -> {
outputArea.setText("");
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new SwingExample().setVisible(true);
});
}
}
Code Explanation
- JFrame: the main window.
setDefaultCloseOperation(EXIT_ON_CLOSE)closes the app when the X button is clicked. - Layout:
GridLayout(3, 2)creates a 3-row x 2-column grid.BorderLayoutdivides areas into NORTH, CENTER, SOUTH, and so on. - Event handling:
submitBtn.addActionListener(e -> { ... })— a lambda as an ActionListener.eis an ActionEvent. - JOptionPane.showMessageDialog() displays a popup dialog.
- SwingUtilities.invokeLater() ensures the GUI is created on the Event Dispatch Thread (EDT) — Swing's dedicated thread.
Everyday Example
A simple calculator with Swing:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Kalkulator extends JFrame {
JTextField input1, input2;
JLabel resultLabel;
public Kalkulator() {
setTitle("Kalkulator");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 5, 5));
add(new JLabel("Number 1:"));
input1 = new JTextField();
add(input1);
add(new JLabel("Number 2:"));
input2 = new JTextField();
add(input2);
JButton addBtn = new JButton("+");
add(addBtn);
JButton multiplyBtn = new JButton("×");
add(multiplyBtn);
JButton subtractBtn = new JButton("-");
add(subtractBtn);
JButton divideBtn = new JButton("÷");
add(divideBtn);
addBtn.addActionListener(e -> calculate("+"));
multiplyBtn.addActionListener(e -> calculate("×"));
subtractBtn.addActionListener(e -> calculate("-"));
divideBtn.addActionListener(e -> calculate("÷"));
}
void calculate(String op) {
try {
double a = Double.parseDouble(input1.getText());
double b = Double.parseDouble(input2.getText());
double r = switch (op) {
case "+" -> a + b;
case "-" -> a - b;
case "×" -> a * b;
case "÷" -> { if (b == 0) throw new ArithmeticException(); yield a / b; }
default -> 0;
};
JOptionPane.showMessageDialog(this, "Result: " + r);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Invalid input!");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Kalkulator().setVisible(true));
}
}
Summary
Swing is a GUI toolkit that is still relevant for Java desktop apps. For new applications, consider JavaFX (modern, CSS styling) or Jetpack Compose for Desktop (declarative). However, understanding Swing helps you grasp the concepts of event-driven programming and layout management.