Skip to content
Unit 2 Syllabus Note· GUI Programming

GUI Programming

Comprehensive exam revision notes for BCA-432E Unit 2 (Windows Forms, Controls, Menus & Exception Handling). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

GUI Programming

Windows Forms, Controls, Menus & Exception Handling

Core Definitions & Key Concepts

What is a Layout Manager in GUI programming

A Layout Manager is an object implementing the LayoutManager interface responsible for automatically determining the size, position, and arrangement of child components inside a container based on available space, fonts, and platform resolution.

Name the 5 standard Layout Managers in Java AWT/Swing

  1. `FlowLayout` (arranges components in a left-to-right row, wrapping as needed)
  2. `BorderLayout` (divides container into 5 zones: North, South, East, West, Center)
  3. `GridLayout` (arranges components into a rectangular grid of equal-sized cells)
  4. `GridBagLayout` (sophisticated grid allowing components to span multiple cells with variable sizes)
  5. `CardLayout` (stacks components like a deck of cards, showing one card at a time).

What is the default layout manager for JFrame and JPanel

  • Default for JFrame (content pane): `BorderLayout`
  • Default for JPanel: `FlowLayout`

The Delegation Event Model

The standard event handling architecture comprising three participants:

  1. Event Source: Component where user action occurs (e.g., JButton).
  2. Event Object: Encapsulates information about the event (e.g., ActionEvent).
  3. Event Listener: Interface implemented by handler object registered with the source (addActionListener()).

What is the difference between an Event Listener and an Event Adapter

  • Listener: An interface containing one or more abstract callback methods; implementing classes must override every method (e.g., MouseListener has 5 methods).
  • Adapter: An abstract class providing default empty implementations for all listener methods, allowing developers to override only the specific methods they need (e.g., MouseAdapter).

List the 5 callback methods of the MouseListener interface

  1. mouseClicked(MouseEvent e)
  2. mousePressed(MouseEvent e)
  3. mouseReleased(MouseEvent e)
  4. mouseEntered(MouseEvent e)
  5. mouseExited(MouseEvent e)

What is the difference between MouseListener and MouseMotionListener

  • MouseListener: Handles discrete mouse button clicks, presses, releases, and entering/exiting component boundaries.
  • MouseMotionListener: Handles continuous mouse movement (mouseMoved) and mouse dragging with a button pressed (mouseDragged).

Key Events and the KeyListener interface

KeyListener handles keyboard input via 3 methods:

  1. keyPressed(KeyEvent e): Key pressed down.
  2. keyReleased(KeyEvent e): Key released.
  3. keyTyped(KeyEvent e): Unicode character typed (excludes modifier keys like Shift/Ctrl).

How do Anonymous Inner Classes simplify event handling in Java

They allow instantiating and implementing an event listener interface directly at the point of registration without declaring a separate named class (e.g., btn.addActionListener(new ActionListener() { ... }); or Java 8 lambda btn.addActionListener(e -> ...);).

What happens if a component is added to BorderLayout without specifying a region

It defaults to the `BorderLayout.CENTER` region. Any previously existing component in that region is replaced.

Conceptual & Architectural Analysis

Compare the 5 Core Layout Managers with Visual Schematics and Properties

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ BORDERLAYOUT ]                      [ GRIDLAYOUT (2x2) ]
+---------------------------+        +-------------+-------------+
|        NORTH              |        |   Cell 1    |   Cell 2    |
+-------+-----------+-------+        +-------------+-------------+
| WEST  |  CENTER   | EAST  |        |   Cell 3    |   Cell 4    |
+-------+-----------+-------+        +-------------+-------------+
|        SOUTH              |        (All cells identical dimensions)
+---------------------------+
Layout ManagerCell DimensionsSpanning Multiple Cells?Wrapping Behavior
`FlowLayout`Preferred component sizeNoWraps to next row when line fills
`BorderLayout`Varies by region (Center expands)Regions fixedNo wrapping
`GridLayout`Strict equal dimensionsNoRigid grid rows and columns
`GridBagLayout`Dynamic per componentYes (gridwidth, gridheight)Most flexible, highly configurable
`CardLayout`Fills container entirelyNoShows one component layer at a time

The Delegation Event Model Architecture with an Interaction Sequence Diagram

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ USER ] ---> [ EVENT SOURCE (JButton) ]
                     |
                     | 1. Generates ActionEvent object
                     v
              [ ActionEvent Object ]
                     |
                     | 2. Iterates over registered listeners
                     v
              [ EVENT LISTENER (ActionListener) ]
                     |
                     | 3. Invokes actionPerformed(ActionEvent e)
                     v
              [ Business Logic Execution ]
  • Decouples event generation from event handling; allows multiple independent listeners to register with a single event source.

GridBagConstraints Key Parameters in GridBagLayout

  1. gridx, gridy: Column and row coordinate where component starts.
  2. gridwidth, gridheight: Number of columns/rows the component spans.
  3. weightx, weighty: Proportional expansion factor when window is resized.
  4. fill: How component expands if cell is larger (NONE, HORIZONTAL, VERTICAL, BOTH).
  5. insets: External padding around component (Insets(top, left, bottom, right)).

Java AWT Event Hierarchy and Semantic vs Low-Level Events

  • Low-Level Events: Represent direct raw hardware inputs or window states: MouseEvent, KeyEvent, FocusEvent, WindowEvent, ComponentEvent.
  • Semantic Events: Represent high-level user interface actions abstracted from hardware: ActionEvent (button clicked/enter pressed), ItemEvent (checkbox toggled), AdjustmentEvent (scrollbar scrolled).

Mouse Adapter Classes and Code Minimization

Implementing MouseListener requires writing 5 methods, even if you only care about mouseClicked. MouseAdapter provides default empty bodies:

Java
1component.addMouseListener(new MouseAdapter() {
2 @Override
3 public void mouseClicked(MouseEvent e) {
4 System.out.println("Clicked at: " + e.getX() + ", " + e.getY());
5 }
6});

In-Depth Analysis & Implementation

Develop a Complete Calculator GUI Demonstrating BorderLayout, GridLayout, and Event Action Delegation

System Architecture / Concept DiagramHorizontal Scroll Enabled
package com.mjpru.bca.gui;

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

public class CalculatorGUI extends JFrame implements ActionListener {
    private JTextField displayField;
    private double num1 = 0, num2 = 0, result = 0;
    private char operator = ' ';
    private boolean startNewNumber = true;

    public CalculatorGUI() {
        setTitle("Standard Calculator");
        setSize(320, 420);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(8, 8));

        // Top Display Field
        displayField = new JTextField("0");
        displayField.setEditable(false);
        displayField.setFont(new Font("Segoe UI", Font.BOLD, 28));
        displayField.setHorizontalAlignment(JTextField.RIGHT);
        displayField.setBackground(new Color(245, 245, 245));
        displayField.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        add(displayField, BorderLayout.NORTH);

        // Keypad Panel (4x4 GridLayout)
        JPanel keypadPanel = new JPanel(new GridLayout(4, 4, 6, 6));
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "C", "0", "=", "+"
        };

        for (String text : buttons) {
            JButton btn = new JButton(text);
            btn.setFont(new Font("Segoe UI", Font.BOLD, 18));
            btn.setFocusPainted(false);
            btn.addActionListener(this);
            keypadPanel.add(btn);
        }

        keypadPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
        add(keypadPanel, BorderLayout.CENTER);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();

        if (cmd.charAt(0) >= '0' && cmd.charAt(0) <= '9') {
            if (startNewNumber || displayField.getText().equals("0")) {
                displayField.setText(cmd);
                startNewNumber = false;
            } else {
                displayField.setText(displayField.getText() + cmd);
            }
        } else if (cmd.equals("C")) {
            num1 = num2 = result = 0;
            operator = ' ';
            displayField.setText("0");
            startNewNumber = true;
        } else if (cmd.equals("=")) {
            if (operator != ' ') {
                num2 = Double.parseDouble(displayField.getText());
                switch (operator) {
                    case '+': result = num1 + num2; break;
                    case '-': result = num1 - num2; break;
                    case '*': result = num1 * num2; break;
                    case '/': 
                        if (num2 != 0) result = num1 / num2;
                        else {
                            displayField.setText("Error: Div/0");
                            startNewNumber = true;
                            return;
                        }
                        break;
                }
                displayField.setText(String.valueOf(result));
                operator = ' ';
                startNewNumber = true;
            }
        } else { // Operator (+, -, *, /)
            num1 = Double.parseDouble(displayField.getText());
            operator = cmd.charAt(0);
            startNewNumber = true;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CalculatorGUI().setVisible(true));
    }
}

Mouse and MouseMotion Event Handling with an Interactive Freehand Drawing Canvas Component

Java
1package com.mjpru.bca.gui;
2
3import javax.swing.*;
4import java.awt.*;
5import java.awt.event.MouseAdapter;
6import java.awt.event.MouseEvent;
7import java.awt.image.BufferedImage;
8
9public class DrawingCanvas extends JPanel {
10 private BufferedImage canvasImage;
11 private Graphics2D g2d;
12 private int prevX, prevY;
13
14 public DrawingCanvas(int width, int height) {
15 setPreferredSize(new Dimension(width, height));
16 setBackground(Color.WHITE);
17
18 // Buffer for persistent painting
19 canvasImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
20 g2d = canvasImage.createGraphics();
21 g2d.setColor(Color.WHITE);
22 g2d.fillRect(0, 0, width, height);
23 g2d.setColor(Color.BLACK);
24 g2d.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
25
26 // Adapter handles both press and drag smoothly
27 MouseAdapter mouseHandler = new MouseAdapter() {
28 @Override
29 public void mousePressed(MouseEvent e) {
30 prevX = e.getX();
31 prevY = e.getY();
32 }
33
34 @Override
35 public void mouseDragged(MouseEvent e) {
36 int curX = e.getX();
37 int curY = e.getY();
38 g2d.drawLine(prevX, prevY, curX, curY);
39 repaint(); // Schedules paintComponent()
40 prevX = curX;
41 prevY = curY;
42 }
43 };
44
45 addMouseListener(mouseHandler);
46 addMouseMotionListener(mouseHandler);
47 }
48
49 @Override
50 protected void paintComponent(Graphics g) {
51 super.paintComponent(g);
52 g.drawImage(canvasImage, 0, 0, null);
53 }
54}

Detail the GridBagLayout Mechanism with a Complete Complex Form Layout Implementation

Deep Dive: GridBagLayout and GridBagConstraints

System Architecture / Concept DiagramHorizontal Scroll Enabled
+-------------------------------------------------------------+
| GridBagLayout: Coordinates Grid (x, y) with Multi-span Cells|
| (0, 0) Label  | (1, 0) TextField (gridwidth=2)             |
| (0, 1) Label  | (1, 1) ComboBox  | (2, 1) CheckBox          |
| (0, 2) Button | (1, 2) Button    | (2, 2) Button (Exit)     |
+-------------------------------------------------------------+

GridBagLayout dynamically maintains internal row and column coordinate matrices based on component minimum, preferred, and maximum dimensions, ensuring layouts stay balanced across operating systems.

Important Exam Points & Quick Revision

Examiners frequently ask: Layout Managers comparison table (BorderLayout vs GridLayout vs GridBagLayout), Delegation Event Model architecture, and MouseAdapter vs MouseListener.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Windows Forms, Controls, Menus & Exception Handling.

Weak topic hint

Windows Forms, Controls, Menus & Exception Handling still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.