0% found this document useful (0 votes)
4 views

Web Note (9-10)

The document discusses Java applets, which are small applications embedded in web pages, detailing their architecture, lifecycle methods, and usage in HTML. It also covers event handling in Java using the AWT framework, explaining the Delegation Event Model, event listener interfaces, and the use of adapter classes and inner/anonymous classes for event handling. Additionally, it lists common AWT components for building user interfaces.

Uploaded by

fohicev584
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)
4 views

Web Note (9-10)

The document discusses Java applets, which are small applications embedded in web pages, detailing their architecture, lifecycle methods, and usage in HTML. It also covers event handling in Java using the AWT framework, explaining the Delegation Event Model, event listener interfaces, and the use of adapter classes and inner/anonymous classes for event handling. Additionally, it lists common AWT components for building user interfaces.

Uploaded by

fohicev584
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
You are on page 1/ 7

UNIT-9: Applet

Applet Class and Applet Architecture


An applet is a small application that can be embedded in a webpage and run inside a web browser. Java applets are
designed to be executed within a web page, providing a dynamic user interface. Applets are part of the java.applet package
and have been a key component in Java's history, though modern web development has shifted away from using applets
due to security concerns.
Applet Class:
The Applet class is the foundation for all Java applets. It is part of the java.applet package. The Applet class extends
java.awt.Panel, meaning it can display a graphical user interface (GUI) and handle user input.
Applet Architecture:
• HTML Webpage: Contains the <applet> tag that loads the applet into the browser.
• Applet Viewer: A tool to run and test applets locally.
• Applet: The Java class that provides the functionality to the applet (extends Applet or JApplet).
• Browser: The container that allows applet execution.

Applet Skeleton
A skeleton for an applet includes defining a class that extends Applet and overriding its lifecycle methods (like init(), start(),
stop(), and destroy()).
Basic Applet Skeleton:
import java.applet.Applet;
import java.awt.Graphics;

public class SimpleApplet extends Applet {

// Called when the applet is first loaded


public void init() {
// Initialization code here
}

// Called when the applet starts or when it comes to the foreground


public void start() {
// Code to start or resume operations
}

// Called when the applet is paused or comes to the background


public void stop() {
// Code to stop operations
}

// Called when the applet is destroyed


public void destroy() {
// Cleanup code
}

// Paints the applet to the screen


public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
}
}
Applet Lifecycle Methods
Java applets follow a lifecycle consisting of several methods that are invoked by the browser or applet viewer:
1. init(): This method is called when the applet is first loaded. It is used to initialize resources or set up the applet.
public void init() {
// Initialization code here
}
2. start(): This method is called when the applet is started or brought into the foreground. It is invoked after init() or
when the user revisits the page.
public void start() {
// Code to start the applet
}
3. stop(): This method is called when the applet is stopped, usually when the user navigates away from the page or
the browser window loses focus.
public void stop() {
// Code to stop or pause operations
}
4. destroy(): This method is called when the applet is destroyed. It is used to clean up resources and stop any ongoing
operations.
public void destroy() {
// Cleanup code here
}
5. paint(Graphics g): This method is called whenever the applet needs to redraw itself. This is where the applet
renders its graphics, such as text, images, etc.
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
}

setForeground() and setBackground() Methods


Java provides the setForeground() and setBackground() methods to change the foreground (text color) and background
color of an applet. These methods can be used to set the colors for drawing components.
Usage:
import java.applet.Applet;
import java.awt.Color;

public class ColorApplet extends Applet {


public void init() {
// Set foreground (text) color
setForeground(Color.RED);
// Set background color
setBackground(Color.CYAN);
}

public void paint(Graphics g) {


g.drawString("This is a colored applet!", 20, 20);
}
}
• setForeground(Color c): Sets the text color (foreground).
• setBackground(Color c): Sets the background color.

Using the Status Window


In Java applets, the status window is a small text area below the applet, which can be used to display status messages. It is
especially useful for debugging and showing runtime information to the user.
You can use showStatus(String msg) to display a message in the status window.
Example:
import java.applet.Applet;

public class StatusApplet extends Applet {


public void init() {
showStatus("Applet Initialized");
}

public void start() {


showStatus("Applet Started");
}

public void stop() {


showStatus("Applet Stopped");
}
}

HTML Applet Tag


The <applet> tag is used to embed an applet into an HTML page. The code attribute specifies the applet’s Java class file, and
other attributes define its dimensions, parameters, and options.
Basic HTML Applet Tag:
<applet code="SimpleApplet.class" width="300" height="200">
<!-- Optional parameters can be added here -->
<param name="message" value="Hello from HTML">
</applet>
• code: Specifies the applet's Java class file.
• width and height: Define the size of the applet.
• <param>: Passes parameters to the applet (optional).

Passing Parameters to an Applet


You can pass parameters from the HTML page to the applet using the <param> tag. These parameters are accessible in the
applet using getParameter().
Example:
html
<applet code="MessageApplet.class" width="300" height="200">
<param name="message" value="Hello from HTML">
</applet>
java
import java.applet.Applet;

public class MessageApplet extends Applet {


public void start() {
String message = getParameter("message");
System.out.println("Message: " + message); // Outputs: Hello from HTML
}
}

getCodebase() and getDocumentBase() Methods


The getCodebase() and getDocumentBase() methods are used to retrieve the URL of the applet's codebase and the URL of
the document from which the applet was launched.
1. getCodebase(): Returns the base URL for loading the applet's code.
String codebase = getCodebase().toString();
2. getDocumentBase(): Returns the URL of the document that contains the applet.
String documentBase = getDocumentBase().toString();

Important Notes:
• Security: Applets run in a restricted environment, known as a sandbox, which limits their access to system
resources.
• Deprecated: Applets are largely deprecated in modern browsers due to security concerns and the rise of other
technologies such as JavaScript and HTML5. As of 2015, most modern browsers no longer support Java applets.

UNIT-10: Event Handling and AWT

Event Handling and AWT (Abstract Window Toolkit)


Java provides an event-driven programming model to handle user interactions with graphical user interface (GUI)
components. AWT (Abstract Window Toolkit) is the library that provides the basic components (such as buttons, labels, and
text fields) for building GUIs.
Event handling in AWT is based on the Delegation Event Model. In this model, the event is generated by a component
(called the source) and is received by an object (called the listener) that processes the event.

1. Delegation Event Model


The Delegation Event Model follows the pattern where:
• Events are generated by GUI components (like a button click, mouse movement).
• Event Listeners are used to handle the events. They are registered to listen for specific types of events on specific
components.
• When an event occurs, the event listener processes the event.
Key Components in the Delegation Event Model:
• Source: The component (like a button or text field) where an event occurs.
• Listener: An object that listens for the event and processes it (like ActionListener for button clicks).
• Event: An object that encapsulates the details of the event (like ActionEvent, MouseEvent, etc.).

2. Event Classes
Java provides different event classes to represent various events. These classes contain the information about the event and
are used to pass this information from the source to the listener.
• ActionEvent: Represents events like button clicks, menu selections, etc.
• MouseEvent: Represents mouse events such as clicks, mouse movement, etc.
• KeyEvent: Represents keyboard events (e.g., key presses and releases).
• WindowEvent: Represents events like window opening, closing, etc.
• ItemEvent: Represents item events, such as selecting a check box or a radio button.

3. Sources of Events
The source of an event is the component that generates the event. Some common AWT components that can generate
events include:
• Button: Generates an ActionEvent when clicked.
• TextField: Generates ActionEvent when Enter is pressed.
• Label: Does not generate events by itself, but can listen to other events like mouse clicks.
• Checkbox: Generates ItemEvent when checked or unchecked.
• Mouse: Generates MouseEvent when the mouse is clicked, pressed, or released.
• Keyboard: Generates KeyEvent when keys are pressed or released.
4. Event Listener Interfaces
Java provides various listener interfaces, and the key ones are as follows:
• ActionListener: Handles action events, such as button clicks or menu selections.
public void actionPerformed(ActionEvent e);
• MouseListener: Handles mouse events (click, press, release).
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
• KeyListener: Handles keyboard events (key press, key release).
public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);
• WindowListener: Handles window events like opening and closing.
public void windowOpened(WindowEvent e);
public void windowClosing(WindowEvent e);
public void windowClosed(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDeactivated(WindowEvent e);

5. Event Handling Using Adapter Class


Java provides adapter classes that are abstract implementations of the listener interfaces. These classes provide default
(empty) implementations of all methods of the listener interfaces. You can override only the methods you are interested in.
For example:
• MouseAdapter: An abstract class that implements MouseListener and provides default empty implementations for
all methods.
• KeyAdapter: An abstract class that implements KeyListener.
Example with MouseAdapter:
import java.awt.*;
import java.awt.event.*;

public class MouseAdapterExample extends Frame {


public MouseAdapterExample() {
setSize(400, 300);
setVisible(true);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
});
}

public static void main(String[] args) {


new MouseAdapterExample();
}
}
Here, only the mouseClicked method is overridden. The other methods of MouseListener are not needed.
6. Inner and Anonymous Classes for Event Handling
You can define event listeners using inner classes or anonymous classes for better modularity or conciseness.
Using an Inner Class:
An inner class is a class defined within another class, and it can be used for event handling. For instance, when handling a
button click event, you might define an inner class that implements the ActionListener interface.
import java.awt.*;
import java.awt.event.*;

public class InnerClassExample extends Frame {


Button b;

public InnerClassExample() {
b = new Button("Click Me");
b.setBounds(100, 100, 80, 30);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
add(b);
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new InnerClassExample();
}
}
Using an Anonymous Class:
An anonymous class is a class without a name and is defined at the point of instantiation. This is useful for handling events
concisely without having to write separate class definitions.
import java.awt.*;
import java.awt.event.*;

public class AnonymousClassExample extends Frame {


Button b;

public AnonymousClassExample() {
b = new Button("Click Me");
b.setBounds(100, 100, 80, 30);
// Anonymous class for event handling
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
add(b);
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new AnonymousClassExample();
}
}

7. AWT Classes
Here are some common AWT components used in Java for building user interfaces:
• Label: Displays a single line of text (static content).
Label label = new Label("Hello, World!");
• Button: Represents a clickable button.
Button button = new Button("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
• TextField: A single-line text input field.
TextField textField = new TextField("Default Text");
• TextArea: A multi-line text input field.
TextArea textArea = new TextArea("Default Text");
• Checkbox: A checkbox for selecting/deselecting options.
Checkbox checkbox = new Checkbox("Accept Terms");
• Choice: A dropdown list of items.
Choice choice = new Choice();
choice.add("Option 1");
choice.add("Option 2");
• List: A list of items that can be selected.
List list = new List();
list.add("Item 1");
list.add("Item 2");

Summary
• Event Handling: The Delegation Event Model uses listeners and event sources to manage user actions.
• Event Listener Interfaces: Interfaces like ActionListener, MouseListener, KeyListener, etc., define methods to handle
various events.
• Adapter Classes: Provide default empty implementations of listener interfaces to simplify event handling.
• Inner/Anonymous Classes: Used for concise event handling implementations.
• AWT Components: Classes like Label, Button, TextField, etc., allow creating user interface components.

You might also like