GUI Programming
Building desktop applications with Java Swing and AWT
This work is licensed under CC BY-NC-SA 4.0
© Way-Up 2025
| Component | Purpose |
|---|---|
JFrame |
Main window container |
JPanel |
Container for organizing components |
JButton |
Clickable button |
JLabel |
Display text or images |
JTextField |
Single-line text input |
JTextArea |
Multi-line text input/display |
JCheckBox |
Checkbox for yes/no options |
JComboBox |
Dropdown selection list |
import javax.swing.*;
public class FirstWindow {
public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("My First Window");
// Set the size (width, height)
frame.setSize(400, 300);
// Set close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Center the window on screen
frame.setLocationRelativeTo(null);
// Make it visible
frame.setVisible(true);
}
}
setVisible(true) last, after all components are added
import javax.swing.*;
public class SimpleApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
// Create components
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Click Me!");
// Create a panel to hold components
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
panel.add(button);
// Add panel to frame
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Layout managers control how components are arranged in containers:
panel.setLayout(new FlowLayout());
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(textArea, BorderLayout.CENTER);
panel.setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns
import javax.swing.*;
import java.awt.*;
public class BorderLayoutDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 400);
// BorderLayout is default for JFrame
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JTextArea("Center"), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
ActionListener - Button clicks, menu selectionsMouseListener - Mouse clicks, enter, exitKeyListener - Keyboard inputimport javax.swing.*;
import java.awt.event.*;
public class ButtonClickApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
JButton button = new JButton("Click Me!");
JLabel label = new JLabel("Not clicked yet");
// Add action listener using lambda (modern Java)
button.addActionListener(e -> {
label.setText("Button was clicked!");
});
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.*;
public class CounterApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Counter");
JButton button = new JButton("Increment");
JLabel label = new JLabel("Count: 0");
// Anonymous class implementation
button.addActionListener(new ActionListener() {
private int count = 0;
@Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Count: " + count);
}
});
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class GreetingApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Greeting App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 150);
JLabel nameLabel = new JLabel("Your name:");
JTextField nameField = new JTextField(15);
JButton greetButton = new JButton("Greet");
JLabel outputLabel = new JLabel("");
greetButton.addActionListener(e -> {
String name = nameField.getText();
outputLabel.setText("Hello, " + name + "!");
});
JPanel panel = new JPanel(new FlowLayout());
panel.add(nameLabel);
panel.add(nameField);
panel.add(greetButton);
panel.add(outputLabel);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class SimpleCalculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 200);
// Create components
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JLabel resultLabel = new JLabel("Result: ");
JButton addButton = new JButton("+");
JButton subButton = new JButton("-");
JButton mulButton = new JButton("×");
JButton divButton = new JButton("÷");
// Add event listeners
addButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "+"));
subButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "-"));
mulButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "*"));
divButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "/"));
// Layout
JPanel inputPanel = new JPanel();
inputPanel.add(new JLabel("Number 1:"));
inputPanel.add(num1Field);
inputPanel.add(new JLabel("Number 2:"));
inputPanel.add(num2Field);
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(subButton);
buttonPanel.add(mulButton);
buttonPanel.add(divButton);
frame.setLayout(new BorderLayout());
frame.add(inputPanel, BorderLayout.NORTH);
frame.add(buttonPanel, BorderLayout.CENTER);
frame.add(resultLabel, BorderLayout.SOUTH);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void calculate(JTextField num1, JTextField num2,
JLabel result, String operation) {
try {
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
double res = 0;
switch (operation) {
case "+": res = n1 + n2; break;
case "-": res = n1 - n2; break;
case "*": res = n1 * n2; break;
case "/": res = n1 / n2; break;
}
result.setText("Result: " + res);
} catch (NumberFormatException ex) {
result.setText("Error: Invalid input");
}
}
}
import javax.swing.*;
import java.awt.*;
public class TextAreaExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Area Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 400);
// Create text area
JTextArea textArea = new JTextArea(15, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
// Add scroll pane for large text
JScrollPane scrollPane = new JScrollPane(textArea);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(e -> textArea.setText(""));
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(clearButton, BorderLayout.SOUTH);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class FormExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Registration Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5));
// Text field
panel.add(new JLabel("Name:"));
JTextField nameField = new JTextField();
panel.add(nameField);
// Combo box
panel.add(new JLabel("Country:"));
String[] countries = {"France", "USA", "UK", "Germany"};
JComboBox countryBox = new JComboBox<>(countries);
panel.add(countryBox);
// Checkbox
panel.add(new JLabel("Subscribe:"));
JCheckBox subscribeBox = new JCheckBox("Newsletter");
panel.add(subscribeBox);
// Button
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(e -> {
String name = nameField.getText();
String country = (String) countryBox.getSelectedItem();
boolean subscribed = subscribeBox.isSelected();
JOptionPane.showMessageDialog(frame,
"Name: " + name + "\nCountry: " + country +
"\nSubscribed: " + subscribed);
});
panel.add(submitButton);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
import javax.swing.*;
public class DialogExample {
public static void main(String[] args) {
// Information message
JOptionPane.showMessageDialog(null, "Hello, World!");
// Confirmation dialog
int choice = JOptionPane.showConfirmDialog(null,
"Do you want to continue?",
"Confirm",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
System.out.println("User clicked Yes");
}
// Input dialog
String name = JOptionPane.showInputDialog(null,
"Enter your name:");
System.out.println("Name: " + name);
// Option dialog
String[] options = {"Red", "Green", "Blue"};
int selected = JOptionPane.showOptionDialog(null,
"Choose a color", "Color Picker",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
}
}
import javax.swing.*;
import java.awt.*;
// Better practice: Extend JFrame
public class MyWindow extends JFrame {
private JTextField nameField;
private JLabel greetingLabel;
public MyWindow() {
// Set up the window
setTitle("OOP GUI Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 150);
// Initialize components
initComponents();
// Set location and make visible
setLocationRelativeTo(null);
setVisible(true);
}
private void initComponents() {
nameField = new JTextField(15);
greetingLabel = new JLabel("");
JButton greetButton = new JButton("Greet");
greetButton.addActionListener(e -> handleGreeting());
JPanel panel = new JPanel();
panel.add(new JLabel("Name:"));
panel.add(nameField);
panel.add(greetButton);
panel.add(greetingLabel);
add(panel);
}
private void handleGreeting() {
String name = nameField.getText();
greetingLabel.setText("Hello, " + name + "!");
}
public static void main(String[] args) {
// Use SwingUtilities to ensure thread safety
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
SwingUtilities.invokeLater(() -> new MyWindow());
setDefaultCloseOperationCreate a GUI application for managing a bank account with the following features: