- Diagram the complete Abstract Window Toolkit (AWT) class hierarchy from
java.lang.Objectdown to visual components. - Compare the 5 core Layout Managers: FlowLayout, BorderLayout, GridLayout, CardLayout, and GridBagLayout.
- Explain the Delegation Event Model (Event Sources, Event Objects, Event Listeners) and write an ActionListener implementation.
- Explain the purpose of Adapter Classes (e.g.
WindowAdapter,MouseAdapter) in avoiding boilerplate dummy methods. - Trace the 5-stage Applet Lifecycle (
init(),start(),paint(),stop(),destroy()) and embed applets into HTML with parameters.
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)**!
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.
| 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. |
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()); |
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.
- Event Source: The GUI component that generates the event when the user interacts with it (e.g.
Button,TextField). - Event Object: Encapsulates all state information about the event (inherits from
java.util.EventObject, e.g.ActionEvent,MouseEvent). - 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 Component | Class | Hierarchy & Usage |
|---|---|---|
| MenuBar | java.awt.MenuBar | Attached to Frame via frame.setMenuBar(mb);. The horizontal bar. |
| Menu | java.awt.Menu | Pull-down menu container added to MenuBar (e.g. "File", "Edit"). |
| MenuItem | java.awt.MenuItem | Individual clickable action command added to Menu (e.g. "Open", "Save"). |
| CheckboxMenuItem | java.awt.CheckboxMenuItem | Menu item with a toggle checkmark. |
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.
| 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 Class | Default Layout Manager | Arrangement Mechanism |
|---|---|---|
java.applet.Applet | FlowLayout | Centers components sequentially left-to-right; wraps to next row. |
java.awt.Panel | FlowLayout | Sequential left-to-right flow layout with 5px default gaps. |
java.awt.Frame | BorderLayout | 5 Geographic zones (NORTH, SOUTH, EAST, WEST, CENTER). |
java.awt.Dialog | BorderLayout | Standard 5-zone border layout. |
AWT vs. Swing (Shailendra Sir Q34 — 6 Key Differences):
| Comparison Factor | Abstract Window Toolkit (AWT) | Java Swing |
|---|---|---|
| Component Weight | Heavyweight: backed by underlying native OS peers. | Lightweight: written 100% in pure Java (no OS peers). |
| Package Name | java.awt.* | javax.swing.* |
| Component Prefix | No prefix: Button, Label, TextField. | Prefixed with 'J': JButton, JLabel, JTextField. |
| Look and Feel | Native OS dependent (looks like Windows on Windows, Mac on Mac). | Pluggable Look and Feel: looks identical across all operating systems. |
| Architecture | Simple component hierarchy. | Follows strict Model-View-Controller (MVC) architecture. |
| Advanced Controls | Only basic controls; lacks tables, trees, or tabs. | Rich controls: JTable, JTree, JTabbedPane, JSlider. |
Apache Tomcat vs. Apache HTTP Server (Shailendra Sir Q36):
| Feature | Apache HTTP Server | Apache Tomcat |
|---|---|---|
| Role | Traditional Web Server (serving static HTML, images, CSS, PHP). | Web Container / Servlet & JSP Container. |
| Execution Engine | Written in C; executes native HTTP web requests on port 80. | Written in Java; executes Java Servlets and compiles JSPs on port 8080. |
| Dynamic Java Support | Cannot execute Java servlets directly (needs proxy modules). | Native JVM environment specifically built to execute Java web apps. |
- Applet vs Application Matrix (3 Marks): Applet has no
main(), runs inside browser sandbox, restricted local disk access; Application starts atmain(), runs standalone with full disk access. - Lifecycle State Diagram (3 Marks): Draw the 5-state diagram (Born $\to$ Running $\rightleftharpoons$ Stopped $\to$ Dead) clearly labeling
init(),start(),paint(),stop(), anddestroy(). - Method Explanations (3 Marks): Give exact method signatures with one-sentence technical descriptions.
- HTML Tag (1 Mark): Write the minimal `
• 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.
Verify your conceptual grasp across AWT controls, layout managers, event delegation, and applet lifecycles with this 10-question quiz.