JAVA
BCA-5002: Unit II
Applets, AWT GUI & Event Delegation
🏠
Subject: BCA-5002 (Java) ⭐ Applet Lifecycle & Event Delegation PYQs Day 2 Focus (Distributed Plan)

Unit II: Applets, AWT GUI & Event Delegation

Comprehensive conceptual textbook guide covering AWT Component Hierarchy, GUI Controls, Layout Managers, Delegation Event Model, Adapter Classes, and the 5-Stage Applet Lifecycle with HTML Embedding.

🎯 Unit Learning Objectives:
  1. Diagram the complete Abstract Window Toolkit (AWT) class hierarchy from java.lang.Object down to visual components.
  2. Compare the 5 core Layout Managers: FlowLayout, BorderLayout, GridLayout, CardLayout, and GridBagLayout.
  3. Explain the Delegation Event Model (Event Sources, Event Objects, Event Listeners) and write an ActionListener implementation.
  4. Explain the purpose of Adapter Classes (e.g. WindowAdapter, MouseAdapter) in avoiding boilerplate dummy methods.
  5. Trace the 5-stage Applet Lifecycle (init(), start(), paint(), stop(), destroy()) and embed applets into HTML with parameters.
💡 Conceptual Intuition: Why Did Java Introduce AWT and Applets?
In the mid-1990s, web pages were completely static: plain HTML documents containing black text and blue hyperlinks. There was no JavaScript, no CSS animations, and no video players.
Java revolutionized the World Wide Web by introducing **Applets**: small compiled Java bytecode programs downloaded automatically by the browser and executed inside the client's local JVM. To give these applets buttons, textfields, checkboxes, and graphics, Sun Microsystems created the **Abstract Window Toolkit (AWT)**!
1. Abstract Window Toolkit (AWT) Class Hierarchy
⭐ CSJMU PYQs: 2024–25, 2022–23, 2018 (Define AWT, draw component hierarchy, explain controls)

The Abstract Window Toolkit (AWT) is Java's original package (java.awt) for developing Graphical User Interfaces (GUIs). AWT components are **heavyweight** because each component is backed by an underlying native operating system peer.

java.lang.Object Component (Abstract) Visual Controls Button, Label, TextField, List Container Panel └ Applet Window └ Frame, Dialog
Complete AWT Component and Container Hierarchy
AWT Control Class Name Description & Example Usage
Button java.awt.Button Push button generating an ActionEvent when clicked (e.g. Button b = new Button("Submit");).
Label java.awt.Label Displays a passive single-line read-only string of text (e.g. Label l = new Label("Enter Roll No:");).
TextField java.awt.TextField Single-line text input field allowing user data entry; can mask passwords using setEchoChar('*').
TextArea java.awt.TextArea Multi-line scrollable text editor area.
Checkbox java.awt.Checkbox Two-state toggle button (Checked/Unchecked). Grouped via CheckboxGroup to form mutually exclusive Radio Buttons.
Choice java.awt.Choice Drop-down pop-up menu of selectable items.
2. Layout Managers in AWT
⭐ CSJMU PYQs: 2024–25, 2023–24, 2021 (Compare FlowLayout, BorderLayout, and GridLayout)

A Layout Manager is an object that implements the LayoutManager interface and automatically determines the position and dimensions of components within a Container, ensuring responsive GUI layouts across different screen sizes and operating systems.

Layout Manager Default For Arrangement Behavior Constructor / Syntax
FlowLayout Panel and Applet Arranges components sequentially in a line (left-to-right). When a line fills up, components wrap to the next line. setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
BorderLayout Frame and Window Divides the container into 5 geographic regions: NORTH, SOUTH, EAST, WEST, and CENTER. Center expands to fill remaining space. add(b1, BorderLayout.NORTH); add(b2, BorderLayout.CENTER);
GridLayout Manual assignment Divides the container into a rectangular grid of equal-sized rows and columns. Every cell has identical width and height. setLayout(new GridLayout(3, 2, 5, 5)); // 3 rows, 2 cols
CardLayout Manual assignment Treats each component as a card in a deck, displaying only one card at a time. Ideal for wizard step screens. cardLayout.show(container, "cardName");
GridBagLayout Manual assignment Most flexible and powerful layout manager; components can span multiple rows and columns with varying sizes using GridBagConstraints. setLayout(new GridBagLayout());
3. The Delegation Event Model & Event Handling
⭐ CSJMU PYQs: 2025–26, 2023–24, 2022–23 (Explain Delegation Event Model, Sources, Listeners, and Adapter Classes)

Java handles user interactions (button clicks, keystrokes, mouse moves) using the modern Delegation Event Model introduced in Java 1.1. In this model, the control that receives the user input **delegates** processing to registered listener objects.

The 3 Participants in the Delegation Event Model:
  1. Event Source: The GUI component that generates the event when the user interacts with it (e.g. Button, TextField).
  2. Event Object: Encapsulates all state information about the event (inherits from java.util.EventObject, e.g. ActionEvent, MouseEvent).
  3. Event Listener: An object implementing a specific listener interface that receives and handles the notification (e.g. ActionListener).
Event Class Generated By Corresponding Listener Key Handler Method(s)
ActionEvent Button click, Enter key in TextField, Menu item select ActionListener actionPerformed(ActionEvent e)
MouseEvent Mouse clicked, pressed, released, moved, dragged MouseListener, MouseMotionListener mouseClicked(), mousePressed(), mouseMoved()
KeyEvent Key pressed, released, typed KeyListener keyPressed(), keyReleased(), keyTyped()
WindowEvent Window opened, closed, closing, minimized WindowListener windowClosing(), windowOpened()

Why Do We Need Adapter Classes?

In Java, when a class implements an interface, it is required to provide concrete implementations for every single method declared in that interface. For example, WindowListener declares 7 methods! Even if you only care about closing the window (windowClosing()), you would have to write 6 empty dummy methods!

Solution: Adapter Classes: Java provides abstract adapter classes (such as WindowAdapter, MouseAdapter, KeyAdapter) that provide empty default implementations for all listener methods. You can simply subclass the adapter and override only the single method you need!

// Using WindowAdapter with an Anonymous Inner Class to close a Frame:
frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        System.exit(0); // Gracefully close application
    }
});

Master Exam Code: Complete Runnable AWT GUI Application

Problem (CSJMU 2024–25 & Lab Q14): Write a complete Java AWT program to create a User Registration Form with Labels, TextFields, Radio Buttons (CheckboxGroup), Dropdown Choice, and a Submit Button that handles the click event:

import java.awt.*;
import java.awt.event.*;

public class StudentForm extends Frame implements ActionListener {
    Label lblTitle, lblName, lblGender, lblCity, lblResult;
    TextField tfName;
    CheckboxGroup cbg;
    Checkbox rbMale, rbFemale;
    Choice chCity;
    Button btnSubmit;

    public StudentForm() {
        // 1. Frame setup
        setTitle("Student Registration Portal");
        setSize(380, 360);
        setLayout(new FlowLayout(FlowLayout.CENTER, 15, 12));

        // 2. Instantiate controls
        lblTitle = new Label("--- Student Registration Form ---");
        lblTitle.setFont(new Font("Arial", Font.BOLD, 14));

        lblName = new Label("Full Name:");
        tfName = new TextField(22);

        lblGender = new Label("Gender:");
        cbg = new CheckboxGroup();
        rbMale = new Checkbox("Male", cbg, true);
        rbFemale = new Checkbox("Female", cbg, false);

        lblCity = new Label("Select City:");
        chCity = new Choice();
        chCity.add("Kanpur");
        chCity.add("Lucknow");
        chCity.add("Delhi");
        chCity.add("Varanasi");

        btnSubmit = new Button("Submit Application");
        lblResult = new Label("Status: Awaiting input...");

        // 3. Register Action Listener
        btnSubmit.addActionListener(this);

        // 4. Add controls to Frame
        add(lblTitle);
        add(lblName); add(tfName);
        add(lblGender); add(rbMale); add(rbFemale);
        add(lblCity); add(chCity);
        add(btnSubmit);
        add(lblResult);

        // 5. Close window via WindowAdapter
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });

        setVisible(true);
    }

    // Event Handler Method
    public void actionPerformed(ActionEvent e) {
        String name = tfName.getText();
        String gender = cbg.getSelectedCheckbox().getLabel();
        String city = chCity.getSelectedItem();
        lblResult.setText("Registered: " + name + " (" + gender + ", " + city + ")");
    }

    public static void main(String[] args) {
        new StudentForm();
    }
}

Menus in AWT: MenuBar, Menu & MenuItem

Menu ComponentClassHierarchy & Usage
MenuBarjava.awt.MenuBarAttached to Frame via frame.setMenuBar(mb);. The horizontal bar.
Menujava.awt.MenuPull-down menu container added to MenuBar (e.g. "File", "Edit").
MenuItemjava.awt.MenuItemIndividual clickable action command added to Menu (e.g. "Open", "Save").
CheckboxMenuItemjava.awt.CheckboxMenuItemMenu item with a toggle checkmark.
4. Applet Fundamentals & The 5-Stage Lifecycle
⭐ CSJMU PYQs: 2025–26, 2024–25, 2023–24, 2022–23, 2020, 2017 (Super-high frequency 10-mark question!)

An Applet is a special type of Java program embedded in an HTML web page and executed on a client machine within a Java-enabled web browser or the SDK appletviewer. Every applet extends java.applet.Applet.

BORN init() RUNNING paint(g) stop() STOPPED start() destroy() DEAD
Complete 5-Stage Applet Lifecycle: init() → start() ⇄ stop() → destroy()
Method Signature Invoked By Lifecycle Stage & Responsibility
public void init() Browser / Appletviewer Initialization (Once): Invoked exactly once when the applet is first loaded into memory. Used to allocate memory, load images, and add AWT controls.
public void start() Browser Execution Start / Resume: Invoked immediately after init(), and called every time the user navigates back to the applet's tab. Used to start threads and animations.
public void paint(Graphics g) AWT Paint Subsystem Display / Redraw: Invoked whenever the applet's output needs refreshing (window restored, resized). Takes a Graphics object to render shapes and text.
public void stop() Browser Suspension: Invoked automatically whenever the user navigates away from the web page or minimizes the browser. Used to pause heavy background threads.
public void destroy() Browser Termination (Once): Invoked once before the applet is completely unloaded from RAM. Releases native operating system resources.

Complete Runnable Applet Example with HTML Embedding & Parameters:

// File: BannerApplet.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;

public class BannerApplet extends Applet {
    String msg;

    public void init() {
        setBackground(Color.DARK_GRAY);
        setForeground(Color.WHITE);
        // Read external parameter passed from HTML
        msg = getParameter("city");
        if (msg == null) msg = "Kanpur";
    }

    public void paint(Graphics g) {
        g.setFont(new Font("Arial", Font.BOLD, 18));
        g.drawString("Welcome to CSJMU: " + msg, 40, 60);
        g.drawRect(30, 30, 320, 50);
    }
}

Associated HTML File (BannerApplet.html):

<!-- HTML file to run the applet via appletviewer -->
<html>
  <body>
    <applet code="BannerApplet.class" width="400" height="150">
      <param name="city" value="Kanpur University" />
    </applet>
  </body>
</html>

High-Yield Assignment Code (Shailendra Sir's Questions 28 & 30):

Problem: Draw a Hut/House and Triangles using Graphics class methods (drawLine, drawRect, drawPolygon):

import java.applet.Applet;
import java.awt.*;

public class HutApplet extends Applet {
    public void paint(Graphics g) {
        // 1. Draw Roof (Triangle via drawPolygon)
        int[] xRoof = {150, 80, 220};
        int[] yRoof = {50, 110, 110};
        g.setColor(Color.RED);
        g.fillPolygon(xRoof, yRoof, 3);

        // 2. Draw House Walls (Rectangle)
        g.setColor(Color.ORANGE);
        g.fillRect(90, 110, 120, 100);

        // 3. Draw Door & Window
        g.setColor(Color.DARK_GRAY);
        g.fillRect(135, 150, 30, 60); // Door
        g.setColor(Color.CYAN);
        g.fillRect(105, 125, 25, 25); // Left window
        g.fillRect(170, 125, 25, 25); // Right window

        // 4. Draw Right-Angled Triangle via drawLine
        g.setColor(Color.BLUE);
        g.drawLine(250, 110, 250, 210); // Vertical
        g.drawLine(250, 210, 310, 210); // Base
        g.drawLine(250, 110, 310, 210); // Hypotenuse
    }
}

Default Layout Managers of Java Containers (Shailendra Sir Q31):

Container ClassDefault Layout ManagerArrangement Mechanism
java.applet.AppletFlowLayoutCenters components sequentially left-to-right; wraps to next row.
java.awt.PanelFlowLayoutSequential left-to-right flow layout with 5px default gaps.
java.awt.FrameBorderLayout5 Geographic zones (NORTH, SOUTH, EAST, WEST, CENTER).
java.awt.DialogBorderLayoutStandard 5-zone border layout.

AWT vs. Swing (Shailendra Sir Q34 — 6 Key Differences):

Comparison FactorAbstract Window Toolkit (AWT)Java Swing
Component WeightHeavyweight: backed by underlying native OS peers.Lightweight: written 100% in pure Java (no OS peers).
Package Namejava.awt.*javax.swing.*
Component PrefixNo prefix: Button, Label, TextField.Prefixed with 'J': JButton, JLabel, JTextField.
Look and FeelNative OS dependent (looks like Windows on Windows, Mac on Mac).Pluggable Look and Feel: looks identical across all operating systems.
ArchitectureSimple component hierarchy.Follows strict Model-View-Controller (MVC) architecture.
Advanced ControlsOnly basic controls; lacks tables, trees, or tabs.Rich controls: JTable, JTree, JTabbedPane, JSlider.

Apache Tomcat vs. Apache HTTP Server (Shailendra Sir Q36):

FeatureApache HTTP ServerApache Tomcat
RoleTraditional Web Server (serving static HTML, images, CSS, PHP).Web Container / Servlet & JSP Container.
Execution EngineWritten in C; executes native HTTP web requests on port 80.Written in Java; executes Java Servlets and compiles JSPs on port 8080.
Dynamic Java SupportCannot execute Java servlets directly (needs proxy modules).Native JVM environment specifically built to execute Java web apps.
5. Exam Answer Blueprint: 10-Mark Model Structure
How to Score Full 10 Marks on "Applet vs Application & Applet Lifecycle":
  1. Applet vs Application Matrix (3 Marks): Applet has no main(), runs inside browser sandbox, restricted local disk access; Application starts at main(), runs standalone with full disk access.
  2. Lifecycle State Diagram (3 Marks): Draw the 5-state diagram (Born $\to$ Running $\rightleftharpoons$ Stopped $\to$ Dead) clearly labeling init(), start(), paint(), stop(), and destroy().
  3. Method Explanations (3 Marks): Give exact method signatures with one-sentence technical descriptions.
  4. HTML Tag (1 Mark): Write the minimal `` snippet.
    ⚠️ Common Exam Pitfalls:
    • Writing main() inside an Applet: Applets DO NOT have a main() method! The browser/appletviewer acts as the container and invokes init() directly.
    • Confusing stop() and destroy(): stop() is temporary (invoked when switching tabs; can restart via start()); destroy() is final and unrecoverable.
    6. Unit II Examination Mastery MCQ Quiz

    Verify your conceptual grasp across AWT controls, layout managers, event delegation, and applet lifecycles with this 10-question quiz.