Java AWT Event Handling: A Comprehensive Guide
Java AWT Event Handling
Introduction to Checkboxes
This code demonstrates the use of checkboxes in Java AWT:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CheckBoxDemo extends Applet {
Checkbox cb1 = new Checkbox("Java");
Checkbox cb2 = new Checkbox("C++");
public void init() {
add(cb1);
add(cb2);
}
}
Displaying Messages on Applets
This code shows how to display a message on an applet:
import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Welcome to JavaApplet", 50, 30);
}
}
Applet Parameters
Parameters can be passed to applets using the <PARAM>
tag within the <APPLET>
tag. The getParameter
method retrieves these values.
Syntax:
<APPLET code="MyApplet.class" width=150 height=80>
<PARAM name=parameter1 value=value1>
<PARAM name=parameter2 value=value2>
</APPLET>
Code Example:
import java.applet.Applet;
import java.awt.Graphics;
public class WelcomeParam extends Applet {
String msg = "";
public void init() {
msg = getParameter("Username");
msg = "Welcome " + msg;
}
public void paint(Graphics g) {
g.drawString(msg, 50, 50);
}
}
Document Base and Code Base
The getDocumentBase()
method retrieves the base URL of the document containing the applet, while getCodeBase()
gets the base URL of the applet’s code.
Example:
import java.applet.*;
import java.net.*;
public class DocumentBaseExample extends Applet {
public void init() {
URL documentBase = getDocumentBase();
URL codeBase = getCodeBase();
System.out.println("Document Base: " + documentBase);
System.out.println("Code Base: " + codeBase);
}
}
Event Classes and Handling
Events represent changes in an object’s state. Event sources generate events, and event listeners handle them.
Common Event Classes:
ActionEvent
: Triggered by component activation.AdjustmentEvent
: Generated when scrollbars are used.TextEvent
: Occurs when text is changed.ContainerEvent
: Triggered by adding/removing components.ComponentEvent
: Generated for resize, move, hide, or show actions.ItemEvent
: Occurs when an item is selected from a list.FocusEvent
: Triggered when a component gains keyboard focus.KeyEvent
: Generated for key presses and releases.
Event Delegation Model:
- Event Source: Generates the event.
- Event Object: Encapsulates event information.
- Listener Interface: Defines event handling methods.
- Listener Object: Implements the listener interface and processes events.
Adapter Classes
Adapter classes provide empty implementations for event listener interfaces, simplifying event handling. Examples include MouseAdapter
, KeyAdapter
, and WindowAdapter
.
AWT Class Hierarchy
The AWT class hierarchy defines the relationships between graphical components:
Component
: Base class for graphical objects.Container
: Manages component layout.Window
: Top-level window without borders.Panel
: Container without borders.Frame
: Top-level window with borders and a menu bar.