Object Oriented Programming in JavaUnit 138 min read
Java GUI Programming: AWT vs Swing, Layouts, Controls & Event Handling
Unit 13 of Object Oriented Programming in Java covers Java's GUI frameworks (AWT and Swing), layout managers, event handling, and practical GUI design with AWT/Swing components, complete with real-world examples, code traces, and exam-focused comparisons.
Core Concepts
1. AWT vs. Swing: The Two GUI Frameworks
Java provides two GUI toolkits:
- AWT (Abstract Window Toolkit): Uses native OS components (heavyweight). Limited to platform-specific look-and-feel.
- Swing: Built on AWT (lightweight). Provides platform-independent, customizable components.
Comparison Table
| Feature | AWT | Swing |
|---|---|---|
| Components | Heavyweight (OS-dependent) | Lightweight (pure Java) |
| Look-and-Feel | Native OS style | Customizable (e.g., Nimbus) |
| Performance | Slower (OS-dependent) | Faster (pure Java) |
| Portability | Limited (OS-specific) | High (cross-platform) |
2. Layout Managers: Organizing Components
Layout managers automatically position and resize components. Key managers:
- FlowLayout: Left-to-right, top-to-bottom (default for
JPanel). - BorderLayout: Divides into 5 areas (NORTH, SOUTH, EAST, WEST, CENTER).
- GridLayout: Rows and columns (equal-sized cells).
- BoxLayout: Stacks components vertically/horizontally.
- CardLayout: Displays one "card" at a time (like a flipbook).
graph TD
A["FlowLayout"] -->|"Components flow left-to-right"| B["Example: Buttons in a row"]
C["BorderLayout"] -->|"5 regions"| D["Example: Menu bar (NORTH), buttons (SOUTH)"]
E["GridLayout"] -->|"Equal-sized grid"| F["Example: Calculator buttons"]
G["BoxLayout"] -->|"Vertical/horizontal stack"| H["Example: Form fields"]
I["CardLayout"] -->|"Single visible 'card'"| J["Example: Wizard pages"]Example: BorderLayout in Action
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);
frame.setVisible(true);
State After Adding Components
+---------------------+
| North Button |
+---------------------+
| |
| Center Button |
| |
+---------------------+
| South Button |
+---------------------+
3. Swing Controls: Common Components
Swing provides reusable UI elements:
- JButton: Clickable button.
- JTextField: Single-line text input.
- JTextArea: Multi-line text input.
- JComboBox: Dropdown list.
- JCheckBox: Toggle option.
- JRadioButton: Single-select option (grouped with
ButtonGroup). - JLabel: Static text or image.
- JSlider: Range selector.
mindmap
root((Swing Controls))
JButton
JTextField
JTextArea
JComboBox
JCheckBox
JRadioButton
JLabel
JSliderExample: Event Handling with JButton
JButton button = new JButton("Click Me");
button.addActionListener(e -> {
System.out.println("Button clicked!");
});
4. Event Handling: Responding to User Actions
Events trigger actions (e.g., button clicks, key presses). Key listeners:
- ActionListener: For buttons, menus.
- MouseListener: For mouse clicks/drags.
- KeyListener: For keyboard input.
- ItemListener: For checkboxes/radio buttons.
Trace: Button Click Event
| Step | Action | State After Step |
|---|---|---|
| 1 | User clicks button | ActionEvent fired |
| 2 | actionPerformed() called |
e.getSource() → button reference |
| 3 | Custom logic executes | Output: "Button clicked!" |
In the Real World
eSewa (Nepal):
- Uses Swing/AWT-like frameworks (or modern JavaFX) for its web-based payment GUI.
- Layout Managers:
BorderLayoutfor the main dashboard (menu bar at top, transaction area in center). - Controls:
JTextFieldfor entering phone numbers,JButtonfor "Pay Now."
Khalti (Nepal):
- Event Handling:
ActionListenertriggers payment confirmation when the "Pay" button is clicked. - Example: After clicking "Pay Rs. 500," the system validates input (via
JTextField) and shows a success dialog (JOptionPane).
- Event Handling:
Pathao (Ride-Hailing App):
- GUI Design: Uses
GridLayoutfor the driver list (rows of driver names, ratings, and "Book Ride" buttons). - Real-Time Updates:
ItemListenerupdates the fare display when the user selects a different pickup/drop location.
- GUI Design: Uses
Worked Example: Even/Odd Checker GUI
Task: Create a GUI that checks if a number is even or odd.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EvenOddChecker {
public static void main(String[] args) {
JFrame frame = new JFrame("Even/Odd Checker");
frame.setLayout(new FlowLayout());
JTextField input = new JTextField(10);
JButton check = new JButton("Check");
JLabel result = new JLabel("Result: ");
check.addActionListener(e -> {
try {
int num = Integer.parseInt(input.getText());
result.setText("Result: " + (num % 2 == 0 ? "Even" : "Odd"));
} catch (NumberFormatException ex) {
result.setText("Error: Enter a valid number!");
}
});
frame.add(input);
frame.add(check);
frame.add(result);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
State After User Enters "7" and Clicks "Check"
+---------------------+
| [____] [Check] [Result: Odd] |
+---------------------+
Trace Table
| Step | User Action | Code Execution | Output |
|---|---|---|---|
| 1 | Enters "7" | input.getText() → "7" |
Text field shows "7" |
| 2 | Clicks "Check" | Integer.parseInt("7") → 7 |
|
| 3 | 7 % 2 == 0 → false |
||
| 4 | result.setText("Odd") |
Label shows "Odd" |
Common Pitfalls and Best Practices
Mixed Layout Managers:
- Avoid combining
BorderLayoutandGridLayoutwithout containers (e.g.,JPanel). - Fix: Use nested containers for complex layouts.
- Avoid combining
Threading Issues:
- Swing components must be updated on the Event Dispatch Thread (EDT).
- Fix: Use
SwingUtilities.invokeLater()for long-running tasks.
Memory Leaks:
- Forgetting to
dispose()ofJDialogorJFramecan leak resources. - Fix: Override
WindowListeneror usesetDefaultCloseOperation().
- Forgetting to
Exam Tip
Differentiate AWT vs. Swing:
- Always mention weight (lightweight vs. heavyweight), platform independence, and customization.
- Example answer:
"AWT uses native OS components (heavyweight), making it platform-dependent. Swing, built on AWT, uses lightweight components and supports custom look-and-feel like Nimbus."
Layout Manager Questions:
- Draw the final layout after adding components (e.g.,
BorderLayoutwith NORTH/SOUTH/CENTER). - Example: For a question on
GridLayout(2,2), sketch:+-----+-----+ | A | B | +-----+-----+ | C | D | +-----+-----+
- Draw the final layout after adding components (e.g.,
Event Handling:
- Show the listener interface and trace the event flow (e.g.,
ActionEvent→actionPerformed()). - Example code snippet is worth 3+ marks; always include it.
- Show the listener interface and trace the event flow (e.g.,
Real-World Tie-Ins:
- Link GUI concepts to apps like eSewa (layout managers) or Khalti (event listeners).
- Example: "The 'Pay Now' button in Khalti uses
ActionListenerto trigger payment validation."
Common Exam Questions:
- Short Answer: "List 3 Swing controls" →
JButton,JTextField,JComboBox. - Programming: Always test edge cases (e.g., empty input, non-numeric values in the even/odd checker).
- Short Answer: "List 3 Swing controls" →
Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 13.
Discussion
Loading…