Skip to content
Unit 1 Syllabus Note· GUI Programming

GUI Programming

Comprehensive exam revision notes for BCA-432E Unit 1 (.NET Framework Architecture & Visual Basic Language Primitives). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

GUI Programming

.NET Framework Architecture & Visual Basic Language Primitives

Core Definitions & Key Concepts

What is a Graphical User Interface (GUI) and how does it contrast with a Command Line Interface (CLI)

A GUI enables human-computer interaction through visual graphical metaphors (windows, icons, menus, buttons, pointers - WIMP) using a mouse or touchscreen. A CLI requires textual keyboard commands with strict syntax. GUIs are intuitive, non-linear, and event-driven; CLIs are lightweight, scriptable, and sequential.

The Event-Driven Programming paradigm

In event-driven programming, program flow is determined by asynchronous external events (user mouse clicks, keystrokes, window resizing, timer ticks, network messages) rather than a rigid procedural sequence. The application enters an infinite event loop, waiting for events to dispatch to corresponding handler routines.

What is an Event Dispatch Thread (EDT)

The dedicated background worker thread in GUI frameworks (e.g., Java Swing) responsible for processing UI events, dispatching listener callbacks, and repainting UI components. To prevent race conditions and freezing, all GUI mutations must execute on the EDT.

What is the difference between AWT (Abstract Window Toolkit) and Swing in Java

FeatureJava AWTJava Swing
Component WeightHeavyweight (relies on native OS peers)Lightweight (drawn purely in Java 2D)
Look and FeelPlatform-dependent (looks like host OS)Pluggable Look and Feel (identical on all OS)
Component SetBasic set (Button, Label, Choice)Rich set (JTree, JTable, JTabbedPane)
ExtensibilityHard to customizeHighly customizable via component painting

What is a Window Manager in operating systems

System software that controls the placement, appearance, borders, title bars, minimizing, maximizing, and stacking order of application windows within a graphical desktop environment.

What is a Modal Dialog Box vs Modeless Dialog Box

  • Modal Dialog: Blocks interaction with all other windows of the parent application until the dialog is closed (e.g., File Save, Confirm Exit).
  • Modeless (Non-Modal) Dialog: Allows users to switch focus between the dialog and parent windows without closing it (e.g., Find & Replace).

The Role of the Message Loop (Event Loop) in Windows GUI

In the Win32 API, the message loop continuously retrieves messages from the application's message queue via GetMessage(), translates virtual keystrokes via TranslateMessage(), and routes them to the window procedure via DispatchMessage().

What is a Widget (Control) in GUI systems

An elemental visual building block of a graphical interface that displays information or accepts user input (e.g., JButton, JTextField, JCheckBox, JComboBox).

What does MVC stand for in GUI architecture

  • Model: Maintains application data and business state.
  • View: Renders visual presentation of the data on screen.
  • Controller / Delegate: Handles user input events and updates the Model/View accordingly (Swing uses a unified UI delegate architecture).

Why should long-running operations never be executed directly inside a button click listener

Because button click listeners execute synchronously on the Event Dispatch Thread (EDT). If a long calculation, file download, or database query blocks the EDT, the GUI stops responding to repaints and user clicks, causing the window to freeze ('Not Responding').

Conceptual & Architectural Analysis

The Architecture of the Event Dispatch Thread (EDT) and SwingUtilities.invokeLater()

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ USER ACTION: Mouse Click / Key Press ]
                 |
                 v
   [ Operating System Event Queue ]
                 |
                 v
   [ AWT / Swing EventQueue ]
                 |
                 v
     +-----------------------+
     |  EVENT DISPATCH       | <--- Processes one event at a time
     |    THREAD (EDT)       | ---> Dispatches to actionPerformed()
     +-----------------------+ ---> Repaints damaged screen regions
                 ^
                 |
   SwingUtilities.invokeLater(Runnable r)  (Pushes task safely to back of EDT queue)
  • Ensures thread safety without requiring explicit synchronization locks on every GUI component.

Compare Heavyweight vs Lightweight GUI Components

AttributeHeavyweight Components (AWT)Lightweight Components (Swing)
Peer RelianceDirectly backed by a native C/C++ OS window peerNo native OS peer; rendered onto parent container
Z-Order StackingAlways render on top of lightweight componentsObey standard transparent Z-order layering
Shape & TransparencyRectangular and opaque onlySupport arbitrary non-rectangular shapes & alpha transparency
Memory FootprintConsumes OS system window handlesMinimal memory overhead; manages own painting

The Win32 Message Loop and Window Procedure Architecture

C
1MSG msg;
2// WinMain message pump loop
3while (GetMessage(&msg, NULL, 0, 0) > 0) {
4 TranslateMessage(&msg); // Translates WM_KEYDOWN to WM_CHAR
5 DispatchMessage(&msg); // Calls WindowProc(hwnd, msg, wParam, lParam)
6}
  • The operating system routes window messages (WM_PAINT, WM_LBUTTONDOWN, WM_DESTROY) to the application's callback WindowProc function.

The Component Hierarchy in Java Swing (JComponent, Container, Component)

System Architecture / Concept DiagramHorizontal Scroll Enabled
java.lang.Object
   └── java.awt.Component (Base UI class: bounds, fonts, colors)
         └── java.awt.Container (Can hold child components)
               ├── java.awt.Window
               │     └── javax.swing.JFrame (Top-level desktop window)
               └── javax.swing.JComponent (Base Swing class)
                     ├── javax.swing.JPanel (Generic container)
                     ├── javax.swing.AbstractButton (JButton, JToggleButton)
                     └── javax.swing.text.JTextComponent (JTextField, JTextArea)

Pluggable Look and Feel (PLAF) in Java Swing

Swing separates component models from their visual rendering using UI delegates (ComponentUI). Applications can switch visual themes dynamically at runtime (e.g., Metal, Nimbus, Windows, Motif) via UIManager.setLookAndFeel(), without altering application business logic.

In-Depth Analysis & Implementation

Develop a Complete Enterprise Java Swing Application Demonstrating Proper EDT Initialization, Exception Handling, and Visual Layout

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 StudentRegistrationApp extends JFrame {
    private JTextField nameField, rollField;
    private JComboBox<String> courseCombo;
    private JTextArea outputArea;
    private JButton submitBtn, clearBtn;

    public StudentRegistrationApp() {
        // 1. Configure Top-Level JFrame Window
        setTitle("MJPRU BCA Student Portal - GUI Demonstration");
        setSize(550, 420);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // Center on screen
        setLayout(new BorderLayout(10, 10));

        // 2. Form Input Panel (GridBagLayout for structured alignment)
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createTitledBorder("Candidate Registration Details"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(6, 6, 6, 6);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // Roll Number Row
        gbc.gridx = 0; gbc.gridy = 0;
        formPanel.add(new JLabel("Roll Number:"), gbc);
        gbc.gridx = 1;
        rollField = new JTextField(15);
        formPanel.add(rollField, gbc);

        // Student Name Row
        gbc.gridx = 0; gbc.gridy = 1;
        formPanel.add(new JLabel("Candidate Name:"), gbc);
        gbc.gridx = 1;
        nameField = new JTextField(15);
        formPanel.add(nameField, gbc);

        // Course Selection Combo
        gbc.gridx = 0; gbc.gridy = 2;
        formPanel.add(new JLabel("Enrolled Course:"), gbc);
        gbc.gridx = 1;
        String[] courses = {"BCA (Full Time)", "MCA", "B.Tech CSE", "B.Sc IT"};
        courseCombo = new JComboBox<>(courses);
        formPanel.add(courseCombo, gbc);

        add(formPanel, BorderLayout.NORTH);

        // 3. Central Output Display Area
        outputArea = new JTextArea(8, 40);
        outputArea.setEditable(false);
        outputArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
        JScrollPane scrollPane = new JScrollPane(outputArea);
        scrollPane.setBorder(BorderFactory.createTitledBorder("Registration Output Log"));
        add(scrollPane, BorderLayout.CENTER);

        // 4. Button Actions Panel
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        submitBtn = new JButton("Register Candidate");
        clearBtn = new JButton("Clear Form");

        buttonPanel.add(clearBtn);
        buttonPanel.add(submitBtn);
        add(buttonPanel, BorderLayout.SOUTH);

        // 5. Attach Event Listeners
        submitBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSubmit();
            }
        });

        clearBtn.addActionListener(e -> {
            rollField.setText("");
            nameField.setText("");
            outputArea.setText("");
            rollField.requestFocus();
        });
    }

    private void handleSubmit() {
        String roll = rollField.getText().trim();
        String name = nameField.getText().trim();
        String course = (String) courseCombo.getSelectedItem();

        // Form Validation
        if (roll.isEmpty() || name.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                "All input fields are mandatory!",
                "Validation Error",
                JOptionPane.WARNING_MESSAGE);
            return;
        }

        outputArea.append(String.format("[REGISTERED] Roll: %-8s | Name: %-20s | Course: %s%n", roll, name, course));
        rollField.setText("");
        nameField.setText("");
        rollField.requestFocus();
    }

    public static void main(String[] args) {
        // Thread-safe EDT launch
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ignored) {}
                new StudentRegistrationApp().setVisible(true);
            }
        });
    }
}

The Pluggable Look and Feel (PLAF) Architecture with Class Diagrams and Custom Look-and-Feel Setup

Swing Pluggable Look and Feel Architecture

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ Component: JButton ]
        |
        +---> Holds: ButtonModel (Pressed, Armed, Rollover states)
        |
        +---> Delegates Painting to: ButtonUI (e.g. WindowsButtonUI / MetalButtonUI)
                                            |
                                            v
                             [ Renders Platform-Specific ]
                             [ Border, Gradient, Shadows ]

Key Architectural Classes:

  1. `UIManager`: Central registry managing installed look-and-feels (LookAndFeelInfo) and defaults table (colors, fonts, borders).
  2. `ComponentUI`: Abstract base class for all UI delegates.
  3. Switching Look and Feel Programmatically:
Java
1try {
2 for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
3 if ("Nimbus".equals(info.getName())) {
4 UIManager.setLookAndFeel(info.getClassName());
5 break;
6 }
7 }
8 // Update existing open component trees
9 SwingUtilities.updateComponentTreeUI(frame);
10} catch (Exception ex) {
11 ex.printStackTrace();
12}

Compare Desktop GUI Architectures: Win32 API vs Java Swing vs Modern Web Electron

DimensionWin32 API (C/C++)Java SwingModern Electron (Chromium + Node)
LanguageC, C++JavaJavaScript, TypeScript, HTML/CSS
Rendering EngineNative Windows GDI/DirectXJava2D software/hardware pipelineChromium Web Engine (Blink)
Cross-PlatformStrictly Windows OSWrite Once, Run Anywhere (JVM)Cross-Platform (Windows, Mac, Linux)
RAM UsageUltra-low (Megabytes)Moderate (50–150 MB)High (200–500+ MB per instance)
UI DevelopmentComplex manual message handlingObject-oriented component treeWeb standards (Flexbox, CSS3, React)

Important Exam Points & Quick Revision

Examiners frequently ask: CLI vs GUI comparison, Heavyweight vs Lightweight components (AWT vs Swing), and Event Dispatch Thread (EDT) safety.

Your reading progress
0%

100% left on this page — finishing it closes the gap for .NET Framework Architecture & Visual Basic Language Primitives.

Weak topic hint

.NET Framework Architecture & Visual Basic Language Primitives 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.