The Java Event Handling Model: Event Delegation Model & Event Class Hierarchy
Overview: When a student clicks Submit, the button is the source and an ActionEvent describes the action.
What is an Event and Event Handling?
- Event: Any change in the state of a GUI component caused by user interaction—such as clicking a
Button, pressing a keyboard key,… - Event Handling: The mechanism that controls an event and decides what action should execute when that event occurs.
Java’s Event Delegation Model (Modern Approach — JDK 1.1+)
- In the old Java 1.0 Event Model, whenever you clicked a button, the event travelled up the entire containment hierarchy until some component…
- Core Idea: Instead of the GUI component (
Button) handling its own click event, the **Event Source (Button) delegates (forwards) the… - The 3 Core Participants of the Event Delegation Model: Event Source (Generator):
- An Event Source must register listeners using a method like
source.addTypeListener(listenerObj)(e.g.,… - Event Object (Message):
- Event Listener (Handler):
View diagram · Figure 4.1: How the Event Delegation Model Works in Java
Ignoring the Event, Self-Contained Events & Delegating Events
- Your DAVV Unit 4 syllabus specifically mentions three ways a Java GUI program can deal with events:
- 1. Ignoring the Event: In the Event Delegation Model, if no listener is registered with an Event Source (for example, the user moves the mouse over a
Frame,… - Benefit: Unlike Java 1.0, zero CPU time is wasted firing events that the programmer does not care about.
- 2. Self-Contained Events (Component Handling Its Own Event): In this approach, the GUI component class (
Frameor a subclass ofButton) acts as BOTH the Event Source and its own Event Listener! - For example, your main class
MyFrame extends Frame implements ActionListenerregisters itself usingbtn.addActionListener(this);… - When to use: Best for small, simple BCA lab programs with 1 or 2 buttons.
- 3. Delegating Events (Separate Handler Class): In large real-world applications, putting 50 button handlers inside a single
Frameclass makes the code messy. - In Delegating Events, the
Frame(UI View) delegates event handling to a completely separate helper class (or an Inner Class /…
The Event Class Hierarchy in Java
- Every event class in Java inherits from the root class
java.util.EventObject, which has a key methodgetSource()(returns the object…
Event Classes, Listener Interfaces & Adapter Classes in Java
Overview: A mouse click includes details such as position, while a key event includes key information.
Relationship Between Event Source, Event Class, Listener Interface & Methods
- In Java’s Event Delegation Model, every GUI Event Source is paired with a specific Event Class (which acts as the parameter) and a…
- 1.
ActionEvent:Button,List(double-click),MenuItem,TextField(Enter key) - 2.
ItemEvent:Checkbox, Radio Button,Choice,List(single select) - 3.
AdjustmentEvent:Scrollbar - 4.
TextEvent:TextField,TextArea(when text changes) - 5.
FocusEvent: AnyComponentgaining or losing keyboard focus - 6.
ContainerEvent:Container(Frame,Panel) when component is added/removed
Detailed Overview of the 9 Syllabus Event Classes
- 1. ActionEvent: Generated when a
Buttonis clicked, aMenuItemis selected, aListitem is double-clicked, or theEnterkey is pressed… - Useful Methods:
String getActionCommand(): Returns the label/command text of the button clicked (e.g.,"Submit").Object getSource(): Returns the reference to the component that fired the event.- 2. AdjustmentEvent: Generated whenever the user moves the slider thumb of a
Scrollbar(up, down, page-up, or drag). - Useful Method:
int getValue()— returns the current integer value of the scrollbar. - 3. ContainerEvent: Generated when a component is dynamically added to (
componentAdded) or removed from (componentRemoved) aContainer(Panel… - Useful Method:
Component getChild()— returns the component that was added or removed.
Adapter Classes in Java (Why & How They Are Used)
- This is a guaranteed 5- to 8-mark question in Unit 4 of DAVV BCA exams!
- The Problem Without Adapter Classes: Suppose you want to close an AWT
Framewhen the user clicks the[X]close button in the top-right corner. - The Solution: What is an Adapter Class?: An Adapter Class is an abstract convenience class in
java.awt.eventthat provides **default empty ({}) implementations… - Without Adapter (implements WindowListener) Must write all 7 methods !
- With Adapter (extends WindowAdapter) WindowAdapter already provides empty bodies for all 7 methods
- List of Listener Interfaces and Their Corresponding Adapter Classes: *(Note: Listener interfaces with only 1 method—like
ActionListener,ItemListener,AdjustmentListener,TextListener—do… WindowListener: 7 methodsMouseListener: 5 methods
View diagram · Figure 4.3: Implementing WindowListener vs Extending WindowAdapter
Networking Basics, Networking Classes & Using java.net Package
Overview: An address identifies the host interface and a port identifies a service endpoint.
Networking Basics in Java
- Java Networking (Network Programming) is the concept of connecting two or more computing devices together over a network (LAN or the…
- 5 Fundamental Networking Terms You Must Know: An address identifies a network interface and a port identifies an endpoint.
- 2. Port Number (0–65535) 16-bit apartment/door number identifying a specific application on that computer (e.g., HTTP = 80)
- 4. Socket (IP + Port) The two-way communication endpoint connecting a Client and a Server
- IP Address (Internet Protocol Address):
- Analogy: The Building Address of a hostel.
- Port Number:
- Analogy: The specific Room Number inside that hostel building!
View diagram · Figure 4.4: Core Building Blocks of Java Network Communication
Overview of the java.net Package (Classes & Interfaces)
- The
java.netpackage provides all the classes and interfaces required for both low-level (Socket/Datagram) and high-level (URL/Web)… - Core Classes in java.net:
InetAddress: Represents an IP address (both IPv4 and IPv6) and resolves Domain Names (DNS) into IP addresses. URL(Uniform Resource Locator): Represents a web address pointing to a resource on the World Wide Web.URLConnection&HttpURLConnection: Represents an active communication link to a URL resource to read headers and content.Socket: Implements the Client-side endpoint for reliable TCP communication.ServerSocket: Implements the Server-side endpoint that listens for incoming TCP client requests.DatagramSocket: A socket for sending and receiving connectionless UDP datagram packets.DatagramPacket: Represents the actual data packet sent or received via UDP.
The InetAddress Class (Working with IP Addresses & DNS)
- The
InetAddressclass encapsulates both the Host Name (e.g.,"www.google.com") and the numerical IP Address (e.g.,… - Important Viva Fact:
InetAddresshas nopublicconstructors! - Important Factory & Instance Methods of InetAddress:
static InetAddress getLocalHost(): Returns theInetAddressobject of your own local computer. static InetAddress getByName(String host): Connects to DNS and returns theInetAddressfor the given domain name.static InetAddress[] getAllByName(String host): Returns an array of all IP addresses mapped to a large website.String getHostName(): Returns the domain/computer name as a String.String getHostAddress(): Returns the raw IP address string (e.g.,"192.168.1.5").
The URL and URLConnection Classes
- A URL (Uniform Resource Locator) is the address of a resource on the Internet.
- A. Methods of the URL Class:
getProtocol(): Returns protocol string (e.g.,"https"). getHost(): Returns host name (e.g.,"www.campusnotes.in").getPort(): Returns explicit port number (or-1if default port is used).getDefaultPort(): Returns default port for the protocol (80for HTTP,443for HTTPS).getFile()/getPath(): Returns the resource path ("/davv/bca/java.html").openConnection(): Returns aURLConnectionobject connected to that webpage!- B. The URLConnection Class: Once you call
url.openConnection(), theURLConnectionobject allows you to inspect HTTP response headers…
View diagram · Structure of a Uniform Resource Locator (URL)
TCP/IP Socket Programming & UDP Datagram Programming in Java
Overview: TCP presents an ordered byte stream, so a program must define where one message ends.
Two Types of Socket Programming in Java
- Java’s
java.netpackage supports two distinct models of network communication between a Client and a Server: - TCP/IP Socket Programming (Connection-Oriented): Uses
SocketandServerSocketclasses. - UDP Datagram Programming (Connectionless): Uses
DatagramSocketandDatagramPacketclasses.
TCP/IP Socket Programming (Socket & ServerSocket)
- TCP/IP (Transmission Control Protocol / Internet Protocol) is a connection-oriented, reliable, two-way stream protocol.
- A. The ServerSocket Class (For the Server): Used by the Server program to listen for incoming client connection requests on a specific port number.
- Constructor:
ServerSocket ss = new ServerSocket(int portNumber); - Key Method —
Socket accept(): Waits (blocks) until a client connects to that port, and once connected, returns a normalSocketobject to communicate… - B. The Socket Class (For the Client): Used by the Client program to initiate a connection with the Server using the Server’s IP address/hostname and Port number.
- Constructor:
Socket s = new Socket(String hostName, int portNumber); - Key Methods:
InputStream getInputStream(): Reads data sent by the other side.
View diagram · Figure 4.5: How TCP/IP Client-Server Socket Communication Works
UDP Datagram Programming (DatagramSocket & DatagramPacket)
- What is a Datagram?
-
- TCP Socket is like a Phone Call (you dial, wait for the other person to pick up
accept(), talk over a dedicated line, and hang…
- TCP Socket is like a Phone Call (you dial, wait for the other person to pick up
-
- UDP Datagram is like dropping a Letter / Postcard in a Post Box!
- Two Core Classes for Datagram Programming:
DatagramPacket(The Envelope + Data Letter): - Constructor for Sending:
- Constructor for Receiving:
DatagramSocket(The Post Box / Courier):
Comparison: TCP/IP Socket vs UDP Datagram Programming
- 1. Protocol Used: TCP (Transmission Control Protocol).
- 2. Connection Type: Connection-Oriented (Dedicated virtual circuit via
accept()). - 3. Java Classes Used:
SocketandServerSocket. - 4. Reliability & Order: 100% Reliable; guarantees zero data loss and preserves exact order.
- 5. Speed & Overhead: Slightly slower due to connection setup, acknowledgments, and error checking.
- 6. Best Real-Life Use Case: Banking transactions, File transfers (FTP), Web browsing (HTTP/HTTPS), Chat apps.