CSC409 Advanced Java Programming

Advanced Java ProgrammingUnit 28 min read

Java Swing & AWT: GUI Programming, Layouts & Event Handling

Unit 2 of Advanced Java Programming covers Java’s GUI frameworks (AWT vs. Swing), core components, layout managers, event handling models, and practical design patterns for interactive applications.

TAKEAWAYS:

  • Understand the AWT vs. Swing trade-offs (native vs. lightweight, performance, platform independence).
  • Master layout managers (Flow, Border, GridBag) and their constructors to design responsive UIs.
  • Implement event-driven programming using listeners (ActionListener, MouseListener) and anonymous inner classes.
  • Build interactive forms with components (JLabel, JTextField, JButton) and handle user input/output.
  • Compare Swing’s component hierarchy (JComponent → AbstractButton → JButton) and its advantages over AWT.
  • Apply best practices for GUI design (modularity, separation of logic/UI, accessibility).

---

## Core Concepts: AWT vs. Swing

### **1. Abstract Window Toolkit (AWT)**
AWT provides **native GUI components** (buttons, text fields) by delegating rendering to the OS. Key features:
- **Heavyweight components**: Rely on OS resources (slower, less portable).
- **Limited customization**: Uses OS-specific look-and-feel (e.g., Windows vs. macOS buttons).
- **Legacy framework**: Mostly replaced by Swing but still used for system tray or native dialogs.

### **2. Swing (JFC)**
Swing is a **pure Java** GUI toolkit built on AWT’s event model but with:
- **Lightweight components**: Drawn by Java (faster, consistent across platforms).
- **Pluggable Look-and-Feel (PLAF)**: Supports themes (Metal, Nimbus, Windows).
- **Rich component set**: `JButton`, `JTable`, `JTree`, etc., with advanced features like tooltips and mnemonics.

#### **Comparison Table**
| Feature               | AWT                          | Swing                        |
|-----------------------|------------------------------|------------------------------|
| **Component Type**    | Heavyweight (OS-dependent)    | Lightweight (Java-drawn)    |
| **Performance**       | Slower (OS rendering)        | Faster (pure Java)          |
| **Portability**       | Poor (OS-specific)           | Excellent (cross-platform)  |
| **Customization**     | Limited                      | High (PLAF, themes)         |
| **Component Prefix**  | `Button`, `TextField`        | `JButton`, `JTextField`     |
| **Use Case**          | Legacy apps, system dialogs  | Modern UIs, enterprise apps  |

**Mermaid Diagram: AWT vs. Swing Hierarchy**
```mermaid
mindmap
  root((GUI Frameworks in Java))
    AWT
      "Heavyweight Components"
      "OS-Dependent Look"
      "Legacy Use (e.g., FileDialog)"
    Swing
      "Lightweight Components"
      "Pure Java Rendering"
      "PLAF Support (Themes)"
      "Extends AWT Event Model"
      "JComponent Hierarchy"
        JComponent
          AbstractButton --> JButton
          JTextComponent --> JTextField
          JScrollPane

Swing Component Hierarchy

Swing components inherit from JComponent (or its subclasses), enabling shared features like:

  • Borders, tool tips, keyboard shortcuts.
  • Layout management (via setLayout()).
  • Event handling (via addActionListener(), etc.).

Key Classes:

classDiagram
    class JComponent {
        <<abstract>>
        +addMouseListener()
        +setLayout()
    }
    class AbstractButton {
        <<abstract>>
        +addActionListener()
    }
    class JButton {
        +JButton(String text)
        +setIcon()
    }
    class JTextField {
        +JTextField(int columns)
        +setText()
    }
    JComponent <|-- AbstractButton
    AbstractButton <|-- JButton
    JComponent <|-- JTextField

Layout Managers

Layout managers automatically position components based on rules. Common types:

1. FlowLayout (Default for JPanel)

  • Behavior: Components left-to-right, top-to-bottom.
  • Constructors:
    FlowLayout()          // Center-aligned, 5px gaps
    FlowLayout(int align) // LEFT, RIGHT, CENTER
    FlowLayout(int align, int hgap, int vgap)
    
  • Example:
    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
    panel.add(new JButton("Red"));
    panel.add(new JButton("Blue"));
    

2. BorderLayout (Default for JFrame)

  • Regions: NORTH, SOUTH, EAST, WEST, CENTER.
  • Example:
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.add(new JButton("Top"), BorderLayout.NORTH);
    

3. GridLayout

  • Behavior: Equal-sized cells in rows/columns.
  • Constructors:
    GridLayout(int rows, int cols)       // Fixed grid
    GridLayout(int rows, int cols, int hgap, int vgap)
    
  • Example:
    JPanel grid = new JPanel(new GridLayout(2, 2));
    grid.add(new JButton("1"));
    grid.add(new JButton("2"));
    

4. GridBagLayout (Advanced)

  • Flexibility: Precise control over component sizes/positions.
  • Key Methods:
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0; gbc.gridy = 0; // Position
    gbc.weightx = 1.0; // Expand horizontally
    

Mermaid Diagram: Layout Manager Flow

flowchart TD
    A[User Adds Component] --> B{Layout Manager?}
    B -->|FlowLayout| C[Left-to-Right, Wrap]
    B -->|BorderLayout| D[5 Regions: N/S/E/W/Center]
    B -->|GridLayout| E[Equal Cells in Grid]
    B -->|GridBagLayout| F[Custom Constraints]

Event Handling

Swing uses delegation-based event handling:

  1. Register a listener (e.g., addActionListener()).
  2. Define event handler (anonymous class or lambda).
  3. Trigger: User action (click, keypress) fires the event.

Example: Sum/Difference Calculator

JButton sumBtn = new JButton("Sum");
sumBtn.addActionListener(e -> {
    int num1 = Integer.parseInt(textField1.getText());
    int num2 = Integer.parseInt(textField2.getText());
    resultLabel.setText("Sum: " + (num1 + num2));
});

Common Listeners

Listener Interface Event Type Example Use Case
ActionListener Button click JButton, JMenuItem
MouseListener Mouse clicks/moves JPanel hover effects
KeyListener Key presses Text input validation
ItemListener ComboBox selection Dropdown menu changes

Practical Example: Color Button Form

Task: Create a form with 3 buttons ("RED", "BLUE", "GREEN") that change a panel’s background.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class ColorChanger {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Color Changer");
        frame.setLayout(new BorderLayout());

        // Color panel (initially white)
        JPanel colorPanel = new JPanel();
        colorPanel.setBackground(Color.WHITE);
        frame.add(colorPanel, BorderLayout.CENTER);

        // Button panel with FlowLayout
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton redBtn = new JButton("RED");
        JButton blueBtn = new JButton("BLUE");
        JButton greenBtn = new JButton("GREEN");

        // Anonymous inner classes for listeners
        redBtn.addActionListener(e -> colorPanel.setBackground(Color.RED));
        blueBtn.addActionListener(e -> colorPanel.setBackground(Color.BLUE));
        greenBtn.addActionListener(e -> colorPanel.setBackground(Color.GREEN));

        buttonPanel.add(redBtn);
        buttonPanel.add(blueBtn);
        buttonPanel.add(greenBtn);
        frame.add(buttonPanel, BorderLayout.SOUTH);

        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Exam Tip

  1. AWT vs. Swing:

    • Always prefer Swing for modern apps (lightweight, customizable).
    • AWT is obsolete except for system dialogs (e.g., FileDialog).
  2. Layout Managers:

    • FlowLayout: Simple, default for JPanel.
    • BorderLayout: Default for JFrame (use NORTH/SOUTH for toolbars).
    • GridBagLayout: Most powerful but complex—use for precise layouts.
  3. Event Handling:

    • Anonymous classes are preferred for short handlers (as in past exam questions).
    • Lambda expressions (Java 8+) simplify syntax:
      button.addActionListener(e -> System.out.println("Clicked!"));
      
  4. Common Pitfalls:

    • Forgetting setVisible(true) on JFrame.
    • Not calling setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
    • Mixing absolute positioning (setBounds()) with layout managers.
  5. Past Exam Patterns:

    • Compare AWT/Swing: Focus on lightweight vs. heavyweight, portability.
    • Code examples: Always include a complete main() method with frame setup.
    • Layout questions: Draw a sketch of the expected UI before coding.

Based on the TU BSc CSIT syllabus for Advanced Java Programming (CSC409), unit 2.

Discussion

Loading…