Topic 9 - Introduction to GUI Programming in Java
Java provides a rich set of libraries to create graphical user interfaces (GUIs) through libraries
like AWT (Abstract Window Toolkit) and Swing. Swing, built on top of AWT, is the more
modern choice for building desktop applications in Java due to its ease of use, versatility, and
customizable components. In a GUI application, components like buttons, text fields, labels, and
windows are used to enable user interaction.
1. Basics of Graphical User Interface (GUI)
A GUI provides a visual interface through which users can interact with a software application.
Key components of a Java GUI include:
• Frames: The main window that holds all other components.
• Panels: Containers used to group components within a frame.
• Components: Elements that the user interacts with, such as buttons, labels, and text
fields.
Java's Swing library provides classes for building GUIs, with the following commonly used
classes:
• JFrame: A window that acts as the main application window.
• JPanel: A container that holds other GUI components.
• JButton: A button that triggers an action when clicked.
• JLabel: A non-editable text display.
• JTextField: A text box for user input.
Example of Basic GUI Components:
Here’s a simple example showing how to create a basic window with a label, a text field, and a
button using Swing.
import javax.swing.*;
public class SimpleGUI {
public static void main(String[] args) {
// Create the main frame (window)
JFrame frame = new JFrame("Simple GUI Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create components
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");
// Create a panel to hold components
JPanel panel = new JPanel();
panel.add(label); // Add label to panel
panel.add(textField); // Add text field to panel
panel.add(button); // Add button to panel
// Add panel to the frame
frame.add(panel);
// Set frame visibility to true
frame.setVisible(true);
}
}
• Explanation:
o JFrame serves as the main window for the GUI.
o JLabel, JTextField, and JButton are added to a JPanel.
o frame.add(panel); adds the panel to the frame.
o frame.setVisible(true); displays the GUI window.
Key Properties of GUI Components
• Resizable: You can control whether a window is resizable.
• Layout Management: The way components are organized in a container. Common
layouts include FlowLayout, BorderLayout, and GridLayout.
• Event Handling: Assigning actions to components (e.g., what happens when a button is
clicked).
2. Building Simple GUI Applications Using OOP Principles
Using Object-Oriented Programming (OOP) principles makes it easier to manage complex GUIs.
By encapsulating functionality in classes and methods, you can create reusable and maintainable
GUI components.
Example: Creating a Simple GUI Application using OOP
This example creates a GUI where a button displays a greeting message when clicked.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GreetingApp extends JFrame {
private JTextField nameField;
private JButton greetButton;
private JLabel greetingLabel;
// Constructor
public GreetingApp() {
// Initialize the frame
setTitle("Greeting Application");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create components
JLabel nameLabel = new JLabel("Enter your name:");
nameField = new JTextField(15);
greetButton = new JButton("Greet");
greetingLabel = new JLabel("");
// Add action listener to the button
greetButton.addActionListener(new GreetButtonListener());
// Add components to a panel
JPanel panel = new JPanel();
panel.add(nameLabel);
panel.add(nameField);
panel.add(greetButton);
panel.add(greetingLabel);
// Add panel to the frame
add(panel);
}
// Inner class to handle button click events
private class GreetButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
greetingLabel.setText("Hello, " + name + "!");
}
}
// Main method to run the application
public static void main(String[] args) {
// Create and show the GUI application
GreetingApp app = new GreetingApp();
app.setVisible(true);
}
}
• Explanation:
o The GreetingApp class extends JFrame, creating a customized GUI frame.
o Components (JLabel, JTextField, JButton) are declared as class variables for
easy access across methods.
o Inner Class GreetButtonListener implements ActionListener to define
behavior for the greetButton when clicked.
o setVisible(true); in the main method makes the GUI visible.
Key OOP Concepts Applied in GUI Programming:
1. Encapsulation: Encapsulate GUI elements and their behavior within classes.
2. Event Handling with Inner Classes: Event listeners (e.g., ActionListener) handle
user interactions like button clicks.
3. Inheritance: Extending JFrame lets the GreetingApp class inherit properties of a
window, making it easier to manage as a single entity.
Event Handling
Event handling is an essential part of interactive GUI applications. Java uses listeners to monitor
and respond to user interactions.
• ActionListener: Used for actions such as button clicks.
• MouseListener: Detects mouse events like clicks and movements.
• KeyListener: Responds to keyboard actions.
Example of ActionListener:
In the previous example, ActionListener is implemented using an inner class,
GreetButtonListener, which overrides the actionPerformed method to handle the button
click.
More Layouts and GUI Components
• Layouts help arrange components within containers. Here are a few common ones:
o FlowLayout: Places components in a row, wrapping when necessary.
o BorderLayout: Divides the container into five regions: North, South, East, West,
and Center.
o GridLayout: Places components in a grid of rows and columns.
Example: Adding a GridLayout
import javax.swing.*;
import java.awt.*;
public class GridExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Grid Layout Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
// Adding buttons to the grid
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.add(new JButton("Button 4"));
frame.setVisible(true);
}
}
• Explanation:
o GridLayout organizes components into a grid, here with 2 rows and 2 columns.