Unit 3: Applet, Event Handling and AWT
Applet:-
An Applet is a small Java program that runs inside a web browser or an
applet viewer. It is part of Java AWT (Abstract Window Toolkit) and is
used to create interactive user interfaces on web pages.
Features of an Applet
1. Runs inside a browser or applet viewer
2.Does not have a main() method
3.Uses AWT for GUI components
4. Can respond to user input like mouse clicks and keyboard events
5.Uses paint(Graphics g) method to draw on the screen
2. Lifecycle of an Applet
An applet has five states:
1. init() → Initializes the applet
2. start() → Starts or resumes the applet
3. paint(Graphics g) → Draws content on the screen
4. stop() → Pauses the applet
5. destroy() → Cleans up resources
3. Creating a Simple Java Applet
Step 1: Create an Applet Class.
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, Java Applet!", 50, 50);
}} //This applet displays text on the screen using drawString()
Run the Applet using an HTML File
Create an HTML file (MyApplet.html) to embed the applet:
<html>
<body>
<applet code="MyApplet.class" width="300"
height="200"></applet>
</body>
</html>
The <applet> tag is used to embed Java applets
in a web page.
Compile and Run
1. Compile the Java File:
javac MyApplet.java
2. Run the Applet in Applet Viewer:
appletviewer MyApplet.html
🔹 appletviewer is used to test applets without a browser.
● Applet Lifecycle Methods (Example):-
import java.applet.Applet;
import java.awt.Graphics;
public class AppletLifecycle extends Applet {
public void init() {
System.out.println("Applet initialized.");
}
public void start() {
System.out.println("Applet started.");
}
public void paint(Graphics g) {
g.drawString("Applet Lifecycle Example", 50,
50);
}
public void stop() {
System.out.println("Applet stopped.");
}
public void destroy() {
System.out.println("Applet destroyed.");
}
}
Run this with appletviewer AppletLifecycle.html and observe lifecycle
messages in the console.
Handling User Events in Applet
Example: Button Click Event in Appletimport java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ButtonApplet extends Applet implements ActionListener {
Button button;
String message = "";
public void init() {
button = new Button("Click Me!");
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
message = "Button Clicked!";
repaint();
}
public void paint(Graphics g) {
g.drawString(message, 50, 100);
}
}
This applet displays a button and changes text when
clicked.
Passing Parameters to Applets
Java allows you to pass parameters to applets via an HTML file using the
<param> tag. These parameters can be retrieved inside the applet using
the getParameter() method.
1. Steps to Pass Parameters to an Applet
Step 1: Create the Java Applet
● The applet retrieves parameters using
getParameter("paramName").
import java.applet.Applet;
import java.awt.Graphics;
public class ParameterApplet extends Applet {
String message;
public void init() {
message = getParameter("msg"); // Get
parameter from HTML
if (message == null) {
message = "No Parameter Passed!";
}
}
public void paint(Graphics g) {
g.drawString(message, 50, 50); // Display
parameter
}
}
The applet fetches the parameter "msg" and displays it on the
screen.
● Create an HTML File
● Pass parameters to the applet using the <param> tag.
<html>
<body>
<applet code="ParameterApplet.class"
width="300" height="200">
<param name="msg" value="Hello, Applet!">
</applet>
</body>
</html>
The msg parameter is passed with the value "Hello, Applet!".
Compile and Run the Applet
1.javac ParameterApplet.java //compile
2.appletviewer ParameterApplet.html // run
This will display "Hello, Applet!" on the screen.
Passing Multiple Parameters
Example: Passing Name and Age
Java Applet
import java.applet.Applet;
import java.awt.Graphics;
public class MultiParamApplet extends Applet {
String name;
int age;
public void init() {
name = getParameter("name");
String ageParam = getParameter("age");
if (name == null) {
name = "Guest";
}
if (ageParam != null) {
age = Integer.parseInt(ageParam);
} else {
age = 0;
}
}
public void paint(Graphics g) {
g.drawString("Hello, " + name + "!", 50, 50);
g.drawString("Your Age: " + age, 50, 70);
}
}
HTML File:
<html>
<body>
<applet code="MultiParamApplet.class" width="300" height="200">
<param name="name" value="Alice">
<param name="age" value="25">
</applet>
</body>
</html>
This applet will display:
Hello, Alice!
Your Age: 25
Event Handling in Java
Event handling in Java allows interactive applications to respond to user
actions like clicking a button, typing in a text field, or moving the mouse.
It is widely used in GUI programming with AWT and Swing.
1. Basics of Event Handling
Java follows the "Event Delegation Model", which consists of:
1. Event Source → The component that generates an event (e.g.,
Button, TextField).
2. Event Object → Contains details about the event (e.g.,
ActionEvent, MouseEvent).
3. Event Listener → An interface that listens for specific events (e.g.,
ActionListener, KeyListener).
4. Event Handler → A method that executes when an event occurs.
2. Handling Button Click Events
The ActionListener interface is used to handle button clicks.
Example: Handling Button Clicks
import java.awt.*;
import java.awt.event.*;
public class ButtonEventExample extends Frame implements
ActionListener {
Button button;
public ButtonEventExample() {
setLayout(new FlowLayout());
button = new Button("Click Me!");
add(button);
button.addActionListener(this); // Register event listener
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
public static void main(String[] args) {
new ButtonEventExample();
}
}
When the button is clicked, the message "Button
clicked!" is printed.
Handling TextField Events
The ActionListener is also used for handling Enter key events in
TextField.
Example: Handling TextField Input
import java.awt.*;
import java.awt.event.*;
public class TextFieldEventExample extends Frame
implements ActionListener {
TextField textField;
Label label;
public TextFieldEventExample() {
setLayout(new FlowLayout());
label = new Label("Enter text and press
Enter:");
textField = new TextField(20);
add(label);
add(textField);
textField.addActionListener(this); // Register
event listener
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
System.out.println("Entered Text: " + text);
}
public static void main(String[] args) {
new TextFieldEventExample();
}
}
Handling Mouse Events:
The MouseListener interface is used to detect mouse clicks,
movement, and hovering.
Example: Handling Mouse Clicks
import java.awt.*;
import java.awt.event.*;
public class MouseEventExample extends Frame implements
MouseListener {
Label label;
public MouseEventExample() {
setLayout(new FlowLayout());
label = new Label("Click anywhere!");
add(label);
addMouseListener(this); // Register event listener
setSize(300, 200);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventExample();
}}When the user clicks inside the window, the coordinates
of the click are displayed.
Handling Keyboard Events
The KeyListener interface detects keyboard presses.
Example: Handling Key Presses
import java.awt.*;
import java.awt.event.*;
public class KeyEventExample extends Frame implements KeyListener {
Label label;
public KeyEventExample() {
setLayout(new FlowLayout());
label = new Label("Type something...");
add(label);
addKeyListener(this); // Register event listener
setSize(300, 200);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyEventExample();
}
}
When the user types, the last key pressed is displayed.