Advance Java ProgrammingUnit 714 min read
Event Handling & Swing GUI: Listeners, Layouts & Components
Unit 7 of Advance Java Programming teaches how Java Swing creates interactive GUIs by handling user events (clicks, keypresses) via listeners and adapters, and how layout managers, containers, and components (buttons, text fields) work together to build responsive desktop applications—with code examples, visual traces,
TAKEAWAYS
- Java Swing uses event listeners (e.g.,
ActionListener,MouseListener) to detect and respond to user actions like button clicks or keypresses, while adapter classes (e.g.,MouseAdapter) simplify implementing multiple listeners by providing empty methods. - Containers (
JFrame,JPanel) and layout managers (FlowLayout,BorderLayout,GridLayout) control how GUI components are arranged and resized, ensuring cross-platform compatibility. - Core Swing components like
JButton,JTextField,JLabel, andJTextAreahandle user input/output, whileJFileChooserandJOptionPaneprovide file dialogs and pop-up messages. - Window events (e.g., closing, minimizing) are managed via
WindowListenerorWindowAdapter, and top-level containers (JFrame,JDialog) are mandatory for standalone GUI applications. - Image display in Swing uses
ImageIconandJLabel, while 2D graphics leverageGraphics2Dfor custom shapes and animations. - Real-world examples: eSewa’s payment buttons use
ActionListenerto trigger transactions; Pathao’s ride request relies onMouseListenerfor map interactions; Ncell’s app usesJOptionPanefor confirmation dialogs.
1. Event Handling in Java Swing
Java Swing decouples event sources (e.g., buttons) from event handlers (code that responds to clicks). This follows the Observer Pattern: components notify listeners when events occur.
1.1 Event Model: Sources, Listeners, and Adapters
An event propagates from a source (e.g., a JButton) to a listener (e.g., an ActionListener). If no listener is registered, the event is ignored.
flowchart TD
A["Event Source\n(JButton, JMenuItem)"] --> B["Event Object\n(e.g., ActionEvent)"]
B --> C["Event Dispatch Thread\n(EDT)"]
C --> D["Event Listener\n(ActionListener, MouseListener)"]
D --> E["Handler Method\n(actionPerformed(), mouseClicked())"]Key Components:
| Component | Role |
|---|---|
| Event Source | GUI component (e.g., JButton, JTextField) that generates events. |
| Event Object | Encapsulates event details (e.g., ActionEvent, MouseEvent). |
| Listener | Interface defining methods to handle events (e.g., ActionListener). |
| Adapter Class | Provides empty implementations of listener methods (e.g., MouseAdapter). |
Why Adapters?
- Implementing multiple listeners (e.g.,
MouseListenerhas 5 methods) is tedious. - Adapter classes (e.g.,
MouseAdapter) let you override only the methods you need.
Example: Adapter Class Usage
JButton btn = new JButton("Click Me");
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(null, "Button clicked!");
}
});
Trace:
- User clicks
btn. MouseAdapter.mouseClicked()is called (no other methods are invoked).
1.2 Common Event Listeners
| Listener Interface | Triggered By | Key Methods |
|---|---|---|
ActionListener |
Button clicks, form submissions | actionPerformed(ActionEvent e) |
MouseListener |
Mouse clicks, drags, enters/exits | mouseClicked(), mouseEntered() |
KeyListener |
Keypresses | keyPressed(KeyEvent e) |
ItemListener |
Checkbox/radio button state changes | itemStateChanged(ItemEvent e) |
WindowListener |
Window open/close/minimize | windowClosing(WindowEvent e) |
Example: ActionListener for a Calculator
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(txtNum1.getText());
double num2 = Double.parseDouble(txtNum2.getText());
double result = num1 + num2;
lblResult.setText("Result: " + result);
}
});
State After Click:
txtNum1: "5.0"
txtNum2: "3.0"
lblResult: "Result: 8.0"
2. GUI Components in Swing
Swing provides components (widgets) to build interfaces. Components are placed inside containers (JFrame, JPanel).
2.1 Core Components
| Component | Purpose | Example Use Case |
|---|---|---|
JButton |
Clickable button | "Submit" in eSewa payment form |
JTextField |
Single-line text input | Username field in login screens |
JTextArea |
Multi-line text input | Comments section in Daraz reviews |
JLabel |
Displays text/images | "Enter Password" in Pathao app |
JComboBox |
Dropdown list | City selection in Ncell app |
JCheckBox |
Toggle option | "Remember Me" checkbox |
JRadioButton |
Single-choice option | Gender selection in forms |
JSlider |
Range selection | Volume control in media players |
Example: JTextField and JTextArea
JTextField txtName = new JTextField(20); // 20 columns wide
JTextArea txtComments = new JTextArea(5, 30); // 5 rows, 30 columns
JScrollPane scrollPane = new JScrollPane(txtComments); // Adds scrollbar
frame.add(scrollPane, BorderLayout.CENTER);
State After Input:
txtName: "John Doe"
txtComments: "This is a long comment...\nthat spans multiple lines."
2.2 Displaying Images
Swing uses ImageIcon to load images and JLabel to display them.
JLabel lblImage = new JLabel(icon);
frame.add(lblImage, BorderLayout.NORTH);
Example: Pathao’s Ride Image
JLabel lblBike = new JLabel(bikeIcon);
lblBike.setHorizontalAlignment(JLabel.CENTER);
frame.add(lblBike);
State:
[Pathao Logo] [Bike Image] [Ride Options]
2.3 2D Graphics in Swing
For custom shapes/animations, override paintComponent(Graphics g) in a JPanel.
public class DrawingPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.drawRect(50, 50, 100, 100); // Draws a rectangle
}
}
Visual Output:
[Red rectangle at (50,50) with width=100, height=100]
3. Layout Managers
Layout managers automatically arrange components based on container size. Common managers:
| Manager | Behavior |
|---|---|
FlowLayout |
Left-to-right, top-to-bottom; wraps to next line if space runs out. |
BorderLayout |
Divides container into 5 regions: NORTH, SOUTH, EAST, WEST, CENTER. |
GridLayout |
Equal-sized cells in a grid (rows × columns). |
GridBagLayout |
Flexible grid with constraints (weight, fill, anchor). |
BoxLayout |
Stacks components vertically/horizontally in a box. |
Example: BorderLayout in eSewa’s Payment Screen
JFrame frame = new JFrame("eSewa Payment");
frame.setLayout(new BorderLayout());
JLabel lblTitle = new JLabel("Payment Details", JLabel.CENTER);
frame.add(lblTitle, BorderLayout.NORTH);
JPanel panel = new JPanel(new GridLayout(2, 2));
panel.add(new JLabel("Amount:"));
panel.add(new JTextField(10));
panel.add(new JLabel("Card:"));
panel.add(new JTextField(10));
frame.add(panel, BorderLayout.CENTER);
JButton btnPay = new JButton("Pay Now");
frame.add(btnPay, BorderLayout.SOUTH);
State:
[Title Bar] [Payment Fields] [Pay Button]
4. Window Events and Top-Level Containers
4.1 WindowListener
Handles window lifecycle events (open, close, iconify, deiconify).
stateDiagram-v2
[*] --> Closed
Closed --> WindowOpen
WindowOpen --> WindowClosing
WindowClosing --> WindowClosed
WindowOpen --> WindowIconified
WindowIconified --> WindowDeiconified
WindowDeiconified --> WindowOpenExample: Handling Window Close
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); // Exit on close
}
});
4.2 Why Top-Level Containers?
JFrame: Standalone window with title bar, borders, and buttons.JDialog: Modal/dialog box (e.g., confirmation dialogs).JApplet: Deprecated (used in browsers; replaced by web apps).
Example: JFrame Creation
JFrame frame = new JFrame("My App");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
State:
[Window with title "My App", 400x300 pixels, visible]
5. Real-World Applications
In the Real World
eSewa’s Payment Buttons
- Idea:
ActionListenertriggers the payment API when a button is clicked. - How: The "Pay Now" button’s
actionPerformed()callseSewaAPI.processPayment().
- Idea:
Pathao’s Ride Request
- Idea:
MouseListenerdetects map clicks to select pickup/drop locations. - How:
mouseClicked()updates the route in real-time using Google Maps API.
- Idea:
Ncell’s App Confirmation Dialogs
- Idea:
JOptionPaneshows pop-ups for critical actions (e.g., "Are you sure?"). - How:
JOptionPane.showConfirmDialog()blocks until the user responds.
- Idea:
NEPSE Stock Dashboard
- Idea:
JSliderlets users adjust time ranges for stock charts. - How:
sliderValueChanged()updates the chart data dynamically.
- Idea:
Worked Example: Compare Two Numbers
Task: Build a GUI that compares two numbers and displays the larger/smaller one.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberComparator {
public static void main(String[] args) {
JFrame frame = new JFrame("Number Comparator");
frame.setLayout(new GridLayout(4, 2, 5, 5));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNum1 = new JLabel("First Number:");
JTextField txtNum1 = new JTextField();
JLabel lblNum2 = new JLabel("Second Number:");
JTextField txtNum2 = new JTextField();
JLabel lblResult = new JLabel("Result:");
JButton btnCompare = new JButton("Compare");
btnCompare.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double num1 = Double.parseDouble(txtNum1.getText());
double num2 = Double.parseDouble(txtNum2.getText());
String result = (num1 > num2) ? "Larger" : "Smaller";
lblResult.setText("Second number is " + result + " than the first.");
} catch (NumberFormatException ex) {
lblResult.setText("Please enter valid numbers!");
}
}
});
frame.add(lblNum1); frame.add(txtNum1);
frame.add(lblNum2); frame.add(txtNum2);
frame.add(btnCompare);
frame.add(lblResult);
frame.pack();
frame.setVisible(true);
}
}
Trace Table:
| Step | txtNum1 | txtNum2 | lblResult |
|---|---|---|---|
| Initial | Result: | ||
| User enters "5.0" | "5.0" | Result: | |
| User enters "3.0" | "5.0" | "3.0" | Result: |
| Clicks "Compare" | "5.0" | "3.0" | Second number is Smaller than the first. |
6. Exam Tip
Focus on:
- Event handling: Know the difference between listeners and adapters. Always show a code snippet with
actionPerformed()ormouseClicked(). - Layout managers: Compare
BorderLayout(5 regions) vs.FlowLayout(left-to-right). Draw a diagram of how components are arranged. - Containers: Explain why
JFrameis mandatory (it provides the window infrastructure). - Components: For
JTextFieldvs.JTextArea, highlight thatJTextAreasupports multi-line input and scrolling. - Real-world tie-ins: Relate
ActionListenerto eSewa buttons orJOptionPaneto Ncell confirmations.
- Event handling: Know the difference between listeners and adapters. Always show a code snippet with
Common Pitfalls:
- Forgetting to call
frame.setVisible(true)(GUI won’t appear). - Not setting
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)(app may hang). - Mixing absolute positioning (e.g.,
setBounds()) with layout managers (can cause misalignment).
- Forgetting to call
Question Patterns:
- "Explain how
JOptionPaneis used in a GUI application." → Answer: For pop-up dialogs (confirmation, input, error messages). - "Draw the state of a
JFrameafter adding components withBorderLayout." → Show a diagram with NORTH/SOUTH/EAST/WEST/CENTER labels. - "Write a program to handle a button click that calculates the sum of two numbers." → Include
ActionListenerand input validation.
- "Explain how
Visual Summary:
mindmap
root((Event Handling in Swing))
EventModel
EventSource
EventSource1(JButton)
EventSource2(JMenuItem)
EventListener
Listener1(ActionListener)
Listener2(MouseListener)
AdapterClass
Adapter1(ActionAdapter)
Adapter2(MouseAdapter)
Components
JTextField
JButton
JLabel
LayoutManagers
BorderLayout
NORTH
SOUTH
EAST
WEST
CENTER
FlowLayout
GridLayout
RealWorld
eSewaButton
PathaoMapClick
NcellDialog
ExamTip
BorderLayoutDiagram
SumCalculatorExampleBased on the TU BCA syllabus for Advance Java Programming (CACS354), unit 7.
Discussion
Loading…