0% found this document useful (0 votes)
6 views26 pages

CS465PC Java OOP Study Notes

The document is a comprehensive study guide for CS465PC: Object Oriented Programming through Java, covering various topics such as thread life cycle, exception handling, applet life cycle, and layout managers. It includes objective questions, detailed explanations of key concepts, and examples for practical understanding. The guide is intended for B.Tech CSE (AI & ML) students at JNTU Hyderabad.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views26 pages

CS465PC Java OOP Study Notes

The document is a comprehensive study guide for CS465PC: Object Oriented Programming through Java, covering various topics such as thread life cycle, exception handling, applet life cycle, and layout managers. It includes objective questions, detailed explanations of key concepts, and examples for practical understanding. The guide is intended for B.Tech CSE (AI & ML) students at JNTU Hyderabad.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS465PC: Object Oriented Programming

Through Java

Comprehensive Study Notes

R22 [Link] CSE (AI & ML) | JNTU Hyderabad

Covers: Thread Life Cycle • Thread Priorities • Multi-Caching • AWT •


Exception Handling • Applets • Layout Managers • Event Handling • Swing • EDM
Table of Contents

# Topic Page

1 1-Mark Objective Questions (All Topics) 3

2 Thread Life Cycle 5

3 Thread Priorities 6

4 Multi-Caching (Synchronization) 7

5 AWT Life Cycle 8

6 Exception Handling & Advantages 9

7 Applet Life Cycle 11

8 Layout Managers 12

9 Event Handling 13

10 AWT Components (Hierarchy, 17 Classes, Methods) 14

11 Smiley Applet Program 17

12 Swing vs Applet 18

13 Event Delegation Model 19


SECTION 1: 1-Mark Objective Questions
1. Which method is used to start a thread in Java?
a) run() b) start() c) init() d) execute()
Ans: b) start()

2. In which state does a thread wait for CPU time after start() is called?
a) Running b) Blocked c) Runnable d) Dead
Ans: c) Runnable

3. Which method puts a thread into the waiting state temporarily?


a) stop() b) yield() c) sleep() d) Both b and c
Ans: d) Both b and c

4. A thread enters the Dead state when:


a) sleep() is called b) run() completes c) yield() is called d) wait() is called
Ans: b) run() completes

5. What is the default priority of a thread in Java?


a) 1 b) 5 c) 10 d) 0
Ans: b) 5 (NORM_PRIORITY)

6. What is the range of thread priorities in Java?


a) 0-9 b) 1-10 c) 0-10 d) 1-100
Ans: b) 1-10

7. Which constant represents minimum thread priority?


a) Thread.MIN_PRIORITY b) [Link] c) [Link] d) [Link]
Ans: a) Thread.MIN_PRIORITY (value = 1)

8. Which keyword is used to achieve thread synchronization in Java?


a) volatile b) transient c) synchronized d) static
Ans: c) synchronized

9. What is a monitor in Java multithreading?


a) A display screen b) A synchronization mechanism c) A thread class d) An exception
Ans: b) A synchronization mechanism (object lock)

10. Which method releases the lock and makes a thread wait?
a) sleep() b) yield() c) wait() d) stop()
Ans: c) wait()

11. Which method is called first when an AWT Frame is displayed?


a) paint() b) update() c) repaint() d) init()
Ans: a) paint()

12. AWT stands for:


a) Abstract Window Toolkit b) Advanced Widget Toolkit c) Application Window Tool d) Abstract Widget Tool
Ans: a) Abstract Window Toolkit

13. Which block is always executed regardless of whether an exception occurs?


a) try b) catch c) finally d) throw
Ans: c) finally
14. Which keyword is used to manually throw an exception?
a) throws b) throw c) catch d) error
Ans: b) throw

15. ArithmeticException is a type of:


a) Checked Exception b) Error c) Unchecked Exception d) Fatal Exception
Ans: c) Unchecked Exception

16. Which class is the parent of all exceptions in Java?


a) Error b) RuntimeException c) Throwable d) Exception
Ans: c) Throwable

17. Which method is called only ONCE during an Applet's lifecycle?


a) start() b) stop() c) init() d) paint()
Ans: c) init()

18. Which method is called when an applet is re-visited?


a) init() b) destroy() c) paint() d) start()
Ans: d) start()

19. Applet class is present in which package?


a) [Link] b) [Link] c) [Link] d) [Link]
Ans: b) [Link]

20. Which layout places components in a single row by default?


a) GridLayout b) FlowLayout c) BorderLayout d) CardLayout
Ans: b) FlowLayout

21. BorderLayout divides the container into how many regions?


a) 3 b) 4 c) 5 d) 6
Ans: c) 5 (North, South, East, West, Center)

22. Which layout manager arranges components in rows and columns of equal size?
a) FlowLayout b) CardLayout c) GridLayout d) BorderLayout
Ans: c) GridLayout

23. Which interface handles button click events?


a) MouseListener b) ActionListener c) KeyListener d) ItemListener
Ans: b) ActionListener

24. What is the method in ActionListener interface?


a) actionDone() b) doAction() c) actionPerformed() d) onAction()
Ans: c) actionPerformed(ActionEvent e)

25. Which AWT component is used for single-line text input?


a) TextArea b) Label c) TextField d) Button
Ans: c) TextField

26. Which AWT component allows multiple selections from a list?


a) Choice b) CheckboxGroup c) List d) ComboBox
Ans: c) List

27. The top-level window without title and border in AWT is called:
a) Frame b) Dialog c) Window d) Panel
Ans: c) Window
28. Swing components are prefixed with:
a) A b) J c) S d) W
Ans: b) J (e.g., JButton, JFrame)

29. Swing is part of which package?


a) [Link] b) [Link] c) [Link] d) [Link]
Ans: c) [Link]

30. Unlike AWT, Swing components are:


a) Heavyweight b) Platform-dependent c) Lightweight d) OS-native
Ans: c) Lightweight (pure Java, not OS-dependent)

31. In the Event Delegation Model, who generates the event?


a) Listener b) Handler c) Source d) Adapter
Ans: c) Source

32. Which method registers a listener for button clicks?


a) setListener() b) addActionListener() c) registerListener() d) onClickListener()
Ans: b) addActionListener()

33. The Event Delegation Model was introduced in Java:


a) 1.0 b) 1.1 c) 2.0 d) 5.0
Ans: b) Java 1.1
SECTION 2: Thread Life Cycle
A thread is a lightweight sub-process, the smallest unit of processing. Java supports multithreading, allowing
multiple threads to run concurrently within a program.

States of a Thread

State Description How Entered

New Thread object created but start() not yet called new Thread()

Runnable Thread is ready to run; waiting for CPU start() called

Running Thread is actively executing JVM scheduler picks it

Blocked/Waiting Thread is waiting for a resource or signal sleep(), wait(), I/O

Dead/Terminated Thread has finished execution run() returns

Thread Life Cycle Diagram


New → (start()) → Runnable → (CPU assigned) → Running → (run() finishes) → Dead
Running → (sleep()/wait()) → Blocked/Waiting → (notified/time up) → Runnable

Key Methods
• start() – Starts the thread; JVM calls run() internally
• run() – Contains the task to be executed
• sleep(ms) – Pauses thread for specified milliseconds
• yield() – Voluntarily gives up CPU to other threads of same priority
• join() – Waits for another thread to finish before continuing
• interrupt() – Interrupts a sleeping or waiting thread

Example: Creating a Thread


class MyThread extends Thread {

public void run() {

[Link]("Thread running: " + getName());

public class Main {

public static void main(String[] args) {

MyThread t = new MyThread();

[Link](); // Moves to Runnable state

}
SECTION 3: Thread Priorities
Thread priority determines the order in which threads are scheduled for execution. A higher priority thread gets
more CPU time. Java uses integer values 1–10 for thread priorities.

Priority Constants

Constant Value Meaning

Thread.MIN_PRIORITY 1 Lowest priority

Thread.NORM_PRIORITY 5 Default priority (all threads)

Thread.MAX_PRIORITY 10 Highest priority

Methods
• setPriority(int p) – Sets thread priority (1–10)
• getPriority() – Returns current thread priority

Example
class PriorityDemo extends Thread {

public void run() {

[Link](getName() + " priority: " + getPriority());

public static void main(String[] args) {

PriorityDemo t1 = new PriorityDemo();

PriorityDemo t2 = new PriorityDemo();

[Link](Thread.MIN_PRIORITY); // 1

[Link](Thread.MAX_PRIORITY); // 10

[Link](); [Link]();

Note: Thread scheduling is JVM and OS-dependent. Priority is a hint, not a guarantee. Thread starvation can
occur if a low-priority thread never gets CPU time.
SECTION 4: Multi-Caching / Thread Synchronization
When multiple threads access shared data simultaneously, data inconsistency (race conditions) can occur.
Synchronization controls access to shared resources using a monitor lock.

Key Concepts
• Race Condition – Two threads update same variable simultaneously, causing incorrect results
• Monitor / Lock – Each Java object has an intrinsic lock; only one thread can hold it at a time
• Critical Section – Code block accessing shared resource
• Deadlock – Two threads waiting for each other's lock forever

Types of Synchronization
1. Synchronized Method
class Counter {

int count = 0;

synchronized void increment() {

count++;

2. Synchronized Block
void increment() {

synchronized(this) {

count++;

Inter-Thread Communication
Used to avoid polling — threads communicate via wait(), notify(), and notifyAll() inside synchronized context.

Method Action

wait() Releases lock and makes thread wait until notified

notify() Wakes up one waiting thread

notifyAll() Wakes up all waiting threads


SECTION 5: AWT Life Cycle
AWT (Abstract Window Toolkit) is Java's original platform-dependent GUI toolkit. A Frame (window) goes
through a specific lifecycle from creation to destruction.

AWT Frame Life Cycle Steps


• 1. Create Frame – Instantiate Frame or subclass
• 2. Set Properties – setSize(), setTitle(), setLayout(), setVisible(true)
• 3. paint(Graphics g) – Called automatically when window is shown/refreshed; used to draw content
• 4. update(Graphics g) – Called before paint(); clears background, then calls paint()
• 5. repaint() – Programmer-triggered refresh; calls update() → paint()
• 6. dispose() – Releases OS resources; window is closed

paint() vs repaint() vs update()

Method Called By Purpose

paint(Graphics g) JVM (auto) Renders GUI components on screen

update(Graphics g) JVM via repaint() Clears screen, then calls paint()

repaint() Programmer Schedules a call to update() → paint()

Basic AWT Frame Example


import [Link].*;

public class MyFrame extends Frame {

public void paint(Graphics g) {

[Link]("Hello AWT!", 100, 100);

public static void main(String[] args) {

MyFrame f = new MyFrame();

[Link]("AWT Demo");

[Link](400, 300);

[Link](true);

}
SECTION 6: Exception Handling & Advantages
An exception is an abnormal event that disrupts normal program flow. Java provides a robust exception
handling mechanism using try, catch, finally, throw, and throws.

Exception Hierarchy
Throwable (root)
• Exception (recoverable)
■ Checked Exceptions: IOException, SQLException, ClassNotFoundException
■ Unchecked Exceptions (RuntimeException): NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException
• Error (JVM-level, unrecoverable): OutOfMemoryError, StackOverflowError

Keywords

Keyword Purpose Example

try Encloses risky code try { int x = 1/0; }

catch Handles specific exception catch(ArithmeticException e)

finally Always executes (cleanup) finally { [Link](); }

throw Manually throw an exception throw new IOException()

throws Declares exceptions a method may throw void f() throws IOException

Exception Handling Example


public class ExceptionDemo {

public static void main(String[] args) {

try {

int[] arr = new int[3];

arr[5] = 10; // ArrayIndexOutOfBoundsException

int result = 10 / 0; // ArithmeticException

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Array error: " + [Link]());

} catch (ArithmeticException e) {

[Link]("Math error: " + [Link]());

} finally {

[Link]("Finally always runs!");

}
Custom Exception
class AgeException extends Exception {

AgeException(String msg) { super(msg); }

class Test {

void checkAge(int age) throws AgeException {

if (age < 18) throw new AgeException('Underage!');

Advantages of Exception Handling

Advantage Explanation

Separation of Error Code Business logic and error handling are separated, making code cleaner

Propagation of Errors Exceptions propagate up the call stack until caught

Grouping Error Types Related exceptions can be grouped in hierarchy and caught together

Normal Flow Maintained Program doesn't crash abruptly; alternate path is provided

Resource Cleanup finally block ensures files/connections are always closed

Meaningful Error Info getMessage(), printStackTrace() give diagnostic details

Custom Exceptions User-defined exceptions for domain-specific error signaling


SECTION 7: Applet Life Cycle
An Applet is a small Java program that runs inside a web browser or applet viewer. It extends
[Link]. Its lifecycle is controlled by the browser/applet viewer.

Five Methods of Applet Lifecycle

Method Called When Frequency

init() Applet is first loaded Once only

start() Applet is started / page is revisited Multiple times

paint(Graphics g) Applet needs to be rendered / repainted Multiple times

stop() User leaves page or applet is minimised Multiple times

destroy() Applet is permanently removed from memory Once only

Lifecycle Flow
Load → init() → start() → paint() ↔ stop() [on revisit: start() again] → destroy()

Basic Applet Example


import [Link];

import [Link];

/*

* <applet code='[Link]' width=300 height=200>

* </applet>

*/

public class HelloApplet extends Applet {

public void init() { [Link]('init called'); }

public void start() { [Link]('start called'); }

public void paint(Graphics g) {

[Link]("Hello from Applet!", 50, 100);

public void stop() { [Link]('stop called'); }

public void destroy() { [Link]('destroy called'); }

}
SECTION 8: Layout Managers
A Layout Manager automatically positions and sizes components within a container. Java provides several
built-in layout managers.

FlowLayout
• Description: Default for Panel/Applet. Places components left to right, wraps to next line.
• Constructor: new FlowLayout([Link], hgap, vgap)
• Use Case: Simple forms, toolbars

BorderLayout
• Description: Divides container into 5 regions: NORTH, SOUTH, EAST, WEST, CENTER.
• Constructor: new BorderLayout(hgap, vgap)
• Use Case: Main application windows

GridLayout
• Description: Places components in equal-sized rows and columns.
• Constructor: new GridLayout(rows, cols, hgap, vgap)
• Use Case: Calculators, keyboards

CardLayout
• Description: Shows one component at a time like a deck of cards.
• Constructor: new CardLayout(hgap, vgap)
• Use Case: Wizards, tabbed panes

GridBagLayout
• Description: Most flexible — components can span multiple rows/cols with constraints.
• Constructor: new GridBagLayout()
• Use Case: Complex forms

BoxLayout
• Description: Arranges components in a single row or column.
• Constructor: new BoxLayout(container, BoxLayout.X_AXIS)
• Use Case: Toolbars, panels

Setting Layout Manager


Frame f = new Frame();

[Link](new FlowLayout()); // Set FlowLayout

[Link](new GridLayout(3, 3)); // 3x3 Grid

[Link](null); // No layout (absolute positioning)


SECTION 9: Event Handling
Event handling allows a program to respond to user actions (mouse clicks, key presses, button clicks). Java
uses the Delegation Event Model (covered in detail in Section 13).

Common Event Listeners & Their Methods


Listener Interface Method(s) Triggered By

ActionListener actionPerformed(ActionEvent) Button click, menu item, Enter key

MouseListener mouseClicked(), mousePressed(), mouseReleased(),Mouse button events


mouseEntered(), mouseExited()

MouseMotionListener mouseMoved(), mouseDragged() Mouse movement

KeyListener keyPressed(), keyReleased(), keyTyped() Keyboard input

WindowListener windowClosing(), windowOpened(), etc. Window events

ItemListener itemStateChanged(ItemEvent) Checkbox, Choice selection

TextListener textValueChanged(TextEvent) TextField, TextArea changes

FocusListener focusGained(), focusLost() Component focus change

AdjustmentListener adjustmentValueChanged() Scrollbar changes

Button Click Event Example


import [Link].*; import [Link].*;

public class ButtonDemo extends Frame implements ActionListener {

Button btn = new Button('Click Me');

Label lbl = new Label('Not clicked yet');

ButtonDemo() {

add(btn); add(lbl);

[Link](this); // Register listener

setSize(300,200); setVisible(true);

public void actionPerformed(ActionEvent e) {

[Link]("Button was clicked!");

public static void main(String[] a) { new ButtonDemo(); }

}
SECTION 10: AWT Components

What is AWT?
AWT (Abstract Window Toolkit) is Java's built-in platform-dependent GUI toolkit introduced in Java 1.0. AWT
components are heavyweight — they rely on the underlying OS for rendering. Package: [Link]

AWT Component Hierarchy


Object

■■■ Component (abstract base for all visual components)

■■■ Button

■■■ Label

■■■ Checkbox

■■■ Choice

■■■ List

■■■ Scrollbar

■■■ TextComponent

■ ■■■ TextField

■ ■■■ TextArea

■■■ Container

■■■ Panel

■ ■■■ Applet

■■■ Window

■■■ Frame

■■■ Dialog

■■■ FileDialog

17 Key AWT Classes — Description, Constructors & Methods


1. Component
Abstract base class for all AWT components.
Constructor(s): N/A (abstract)
Key Methods:
• setSize(w,h) – Set dimensions
• setVisible(bool) – Show/hide component
• setBackground(Color) – Set background color
• setForeground(Color) – Set text/foreground color
• setFont(Font) – Set component font
• repaint() – Request redraw
• getSize() – Returns Dimension

2. Button
A push button that triggers an action event when clicked.
Constructor(s): Button() | Button(String label)
Key Methods:
• setLabel(String) – Set button text
• getLabel() – Get button text
• addActionListener(ActionListener) – Register listener
• setEnabled(bool) – Enable/disable

3. Label
Displays a read-only single line of text. Not editable by the user.
Constructor(s): Label() | Label(String text) | Label(String, int alignment)
Key Methods:
• setText(String) – Change label text
• getText() – Get label text
• setAlignment(int) – LEFT, CENTER, RIGHT

4. TextField
Single-line text input component.
Constructor(s): TextField() | TextField(int cols) | TextField(String text, int cols)
Key Methods:
• getText() – Get entered text
• setText(String) – Set text
• setEchoChar(char) – For passwords
• setEditable(bool) – Make read-only
5. TextArea
Multi-line scrollable text input area.
Constructor(s): TextArea() | TextArea(int rows, int cols) | TextArea(String, rows, cols,
scrollbars)

Key Methods:
• getText() / setText(String) – Get/set content
• append(String) – Add text at end
• insert(String, pos) – Insert at position
• replaceRange(String, start, end)

6. Checkbox
A toggle button (checked or unchecked). Supports item events.
Constructor(s): Checkbox() | Checkbox(String label) | Checkbox(String, bool, CheckboxGroup)
Key Methods:
• getState() – Returns true/false
• setState(bool) – Set checked/unchecked
• getLabel() / setLabel(String)
• addItemListener(ItemListener)

7. CheckboxGroup
Groups Checkbox objects to create radio-button behavior (only one can be selected).
Constructor(s): CheckboxGroup()
Key Methods:
• getSelectedCheckbox() – Get selected option
• setSelectedCheckbox(Checkbox) – Set selection

8. Choice
A drop-down (combo box) allowing single selection.
Constructor(s): Choice()
Key Methods:
• add(String item) – Add an item
• getSelectedItem() – Get selected text
• getSelectedIndex() – Get selected index
• remove(int index) / removeAll()
• addItemListener(ItemListener)
9. List
A scrollable list box; supports single or multiple selections.
Constructor(s): List() | List(int rows) | List(int rows, boolean multiSelect)
Key Methods:
• add(String item) – Add item
• getSelectedItem() / getSelectedItems()
• getSelectedIndex()
• remove(String/int)
• addActionListener() / addItemListener()

10. Scrollbar
A standalone scrollbar (horizontal or vertical) for value selection.
Constructor(s): Scrollbar() | Scrollbar(int orientation) | Scrollbar(int, value, visible, min,
max)

Key Methods:
• getValue() – Get current scroll value
• setValue(int) – Set position
• setMinimum(int) / setMaximum(int)
• addAdjustmentListener()

11. Panel
A generic container used to group components. Has no visible border.
Constructor(s): Panel() | Panel(LayoutManager)
Key Methods:
• add(Component) – Add child component
• setLayout(LayoutManager)
• remove(Component)

12. Frame
Top-level window with title bar, border, and menu bar support.
Constructor(s): Frame() | Frame(String title)
Key Methods:
• setTitle(String) – Set window title
• setSize(w,h) / setVisible(bool)
• setMenuBar(MenuBar)
• setResizable(bool)
• dispose() – Close and release resources
• addWindowListener()
13. Dialog
A pop-up window used for user interaction or displaying messages.
Constructor(s): Dialog(Frame, String title, bool modal)
Key Methods:
• setModal(bool) – Block parent if modal
• setVisible(bool)
• setTitle(String)

14. FileDialog
OS-native file chooser dialog for Open/Save operations.
Constructor(s): FileDialog(Frame, String, int mode) [LOAD or SAVE]
Key Methods:
• getFile() – Get selected filename
• getDirectory() – Get directory path
• setFile(String) – Pre-select a file

15. MenuBar
Container for Menu objects; attached to a Frame.
Constructor(s): MenuBar()
Key Methods:
• add(Menu) – Add a menu
• getMenu(int) – Get menu by index
• setHelpMenu(Menu)

16. Canvas
Blank drawing surface; override paint() for custom graphics.
Constructor(s): Canvas()
Key Methods:
• paint(Graphics g) – Override to draw
• repaint() – Refresh drawing
• addMouseListener() – For interaction

17. Graphics
Abstract class providing drawing methods in paint(). Not instantiated directly.
Constructor(s): Provided by JVM via paint(Graphics g)
Key Methods:
• drawString(String, x, y) – Draw text
• drawLine(x1,y1,x2,y2) – Draw line
• drawRect(x,y,w,h) / fillRect(x,y,w,h)
• drawOval(x,y,w,h) / fillOval(x,y,w,h)
• drawArc(x,y,w,h,start,extent)
• setColor(Color) – Set drawing color
• setFont(Font) – Set text font
SECTION 11: Simple Applet Program — Smiley Face ■
This applet draws a smiley face using AWT's Graphics methods: oval for face and eyes, arc for the smile, and
filled ovals for pupils.

import [Link];

import [Link].*;

/*

* <applet code='[Link]' width='400' height='400'>

* </applet>

*/

public class SmileyApplet extends Applet {

public void paint(Graphics g) {

// --- Background ---

[Link](new Color(255, 255, 200)); // Light yellow

[Link](0, 0, 400, 400);

// --- Face (big yellow circle) ---

[Link]([Link]);

[Link](100, 50, 200, 200); // x, y, width, height

[Link]([Link]);

[Link](100, 50, 200, 200); // Face outline

// --- Left Eye ---

[Link]([Link]);

[Link](145, 110, 35, 35); // White of left eye

[Link]([Link]);

[Link](155, 120, 15, 15); // Left pupil

// --- Right Eye ---

[Link]([Link]);

[Link](220, 110, 35, 35); // White of right eye

[Link]([Link]);

[Link](230, 120, 15, 15); // Right pupil

// --- Nose ---

[Link](new Color(255, 150, 50));

[Link](190, 160, 20, 15); // Small oval nose

// --- Smile (arc) ---


[Link]([Link]);

[Link](140, 170, 120, 70, 0, -180); // Smile arc

// Params: x, y, width, height, startAngle, arcAngle

// 0 = 3 o'clock, -180 = clockwise half circle (smile)

// --- Cheeks ---

[Link](new Color(255, 182, 193)); // Pink

[Link](115, 185, 45, 25); // Left cheek

[Link](240, 185, 45, 25); // Right cheek

// --- Caption ---

[Link](Color.DARK_GRAY);

[Link](new Font('Arial', [Link], 20));

[Link]("Have a Great Day! :)", 100, 310);

How to Run: Compile with javac [Link], then run using AppletViewer: appletviewer
[Link] (the HTML comment tag is embedded in the source).
SECTION 12: Swing — What is it? How is it Different from Applet?

What is Swing?
Swing is Java's advanced GUI toolkit, introduced in Java 1.2 as part of the Java Foundation Classes (JFC). It is
in the [Link] package. Swing components are lightweight — they are rendered entirely in Java without
relying on the OS's native rendering.

Key Swing Components


• JFrame – Top-level window
• JPanel – Generic container
• JButton – Clickable button
• JLabel – Non-editable text/image
• JTextField / JTextArea – Text input
• JComboBox – Drop-down list
• JTable – Tabular data display
• JMenuBar / JMenu / JMenuItem – Menu system
• JDialog – Pop-up dialogs
• JTabbedPane – Tabbed panels

Swing vs AWT vs Applet — Comparison


Feature AWT Swing Applet

Package [Link] [Link] [Link]

Component Type Heavyweight Lightweight Extends Applet (AWT)

Platform Dependency Yes (OS-rendered) No (Java-rendered) Yes (AWT-based)

Look & Feel OS native only Pluggable (Nimbus, Metal) OS native

MVC Architecture No Yes No

Rich Components Basic Advanced (JTable, JTree) Basic

Running Context Standalone app Standalone app Browser / AppletViewer

Deprecated? Mostly Partially (JavaFX preferred) Yes (Java 11+)

Double Buffering Manual Built-in Manual

Basic Swing JFrame Example


import [Link].*;

import [Link].*;

public class SwingDemo extends JFrame {

SwingDemo() {

setTitle("Swing Demo");

setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel lbl = new JLabel('Hello Swing!', [Link]);

[Link](new Font('Arial', [Link], 20));

add(lbl, [Link]);

setVisible(true);

public static void main(String[] a) { new SwingDemo(); }

}
SECTION 13: Event Delegation Model (EDM)
The Event Delegation Model (introduced in Java 1.1) is the standard mechanism for handling GUI events.
Instead of the component handling its own events, it delegates (forwards) the event to a separate listener
object.

Core Participants

Role Who It Is Responsibility

Event Source GUI Component (Button, TextField, etc.) Generates the event when user interacts

Event Object ActionEvent, MouseEvent, KeyEvent, etc. Encapsulates event details (what happened, when, where)

Event Listener Object implementing a Listener interface Receives and handles the event

How the Delegation Works — Step by Step


• Step 1: Create a Source (e.g., Button btn = new Button('OK'))
• Step 2: Create a Listener — a class that implements the listener interface (e.g., ActionListener)
• Step 3: Register the listener with the source: [Link](listenerObject)
• Step 4: User clicks the button → source creates an ActionEvent object
• Step 5: Source delegates (calls) the listener's actionPerformed(event) method
• Step 6: Listener handles the event — updates UI, processes data, etc.

Visual Flow of EDM


User Action → [Source Component] → Event Object Created → Dispatched to → [Registered Listener] →
Handler Method Called

Registration Methods by Event Type


Source Component Listener Interface Registration Method

Button ActionListener addActionListener(al)

TextField ActionListener / TextListener addActionListener(al) / addTextListener(tl)

Checkbox ItemListener addItemListener(il)

Choice ItemListener addItemListener(il)

List ActionListener / ItemListener addActionListener(al)

Scrollbar AdjustmentListener addAdjustmentListener(al)

Any Component MouseListener addMouseListener(ml)

Any Component KeyListener addKeyListener(kl)

Frame / Dialog WindowListener addWindowListener(wl)

Complete EDM Example — Button + Mouse Events


import [Link].*;

import [Link].*;

public class EDMDemo extends Frame

implements ActionListener, MouseListener {

Button btn = new Button('Click Me');

Label status = new Label('Waiting...');

EDMDemo() {

setLayout(new FlowLayout());

add(btn); add(status);

// STEP 3: Register listeners

[Link](this); // 'this' is the listener

[Link](this); // Multiple listeners allowed

setSize(350, 200); setVisible(true);

// STEP 5-6: Handle ActionEvent (button click)

public void actionPerformed(ActionEvent e) {

if ([Link]() == btn) {

[Link]("Button Clicked! Count: " + [Link]());

// MouseListener methods (all must be implemented)

public void mouseEntered(MouseEvent e) {

[Link]("Mouse entered button!");

public void mouseExited(MouseEvent e) {

[Link]("Mouse left button.");

public void mouseClicked(MouseEvent e) {}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e){}

public static void main(String[] a) { new EDMDemo(); }

Adapter Classes — Convenience for Listeners


Adapter classes provide empty implementations of listener interfaces. Extend them to override only the methods
you need (avoids implementing all methods).

Adapter Class Corresponding Interface

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

KeyAdapter KeyListener

WindowAdapter WindowListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

Adapter Class Example


// Using MouseAdapter - override only mouseClicked

[Link](new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

[Link]("Mouse clicked at: "

+ [Link]() + ", " + [Link]());

// No need to implement other 4 MouseListener methods!

});

Advantages of Event Delegation Model


• Clean separation between UI components and business logic
• Multiple listeners can be registered on a single source
• Same listener can handle events from multiple sources
• Better performance than Java 1.0's event model (no event chaining)
• Promotes reusability and modularity

CS465PC | R22 [Link] CSE (AI & ML) | JNTU Hyderabad | Prepared for Exam Preparation

You might also like