0% found this document useful (0 votes)
4 views28 pages

Java Unit3

This document covers event handling in Java, detailing the types of events (foreground and background) and the delegation event model involving sources and listeners. It explains various GUI components such as frames, panels, buttons, checkboxes, radio buttons, labels, text fields, text areas, and combo boxes, along with their respective functionalities and example programs. Additionally, it describes layout managers that control the arrangement of components within containers.

Uploaded by

sammymurugan21
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 views28 pages

Java Unit3

This document covers event handling in Java, detailing the types of events (foreground and background) and the delegation event model involving sources and listeners. It explains various GUI components such as frames, panels, buttons, checkboxes, radio buttons, labels, text fields, text areas, and combo boxes, along with their respective functionalities and example programs. Additionally, it describes layout managers that control the arrangement of components within containers.

Uploaded by

sammymurugan21
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

UNIT-III

Event Handling
An event can be defined as changing the state of an object or behavior by performing
actions.
OR
An event occur when a user interacts with GUI(graphical user interface) and perform an
action. Actions can be a button click, cursor movement, keypress through keyboard or page
scrolling, selecting an item from dropdown menu etc. The [Link] package can be
used to provide various event classes.
Classification of Events
1. Foreground Events
2. Background Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User
Interface (GUI).
ex: clicking on a button, scrolling the scroll bar, cursor moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, hardware failures,
software crashes etc.

Delegation Event model


Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
Listeners: Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.

Event classes and event listener interface


Mouse Events
Occurs when a user interacts with the mouse. A user may click the mouse while interacting
with an application. A user may also release, drag or move the mouse. To capture these
events the MouseListener and MouseMotionListener interface from the [Link]
package are used
MouseListener Interface Methods.
1. void mouseClicked (MouseEvent e): This method is invoked when a mouse button is
clicked. It means the button is pressed and then released on a component.
2. void mouseEntered(MouseEvent e): This method is invoked when the mouse enters a
component.
3. void mouseExited (MouseEvent e): This method is invoked when the mouse exits a
component.
[Link] mousePressed(MouseEvent e): This method is invoked when a mouse button is
pressed on a component.
5. void mouseRelease (MouseEvent e): This method is invoked when a mouse button is
released on a component.

MouseMotionListener Interface Methods.


1. void mouseDragged(MouseEvent e): This method is invoked when a mouse button is
pressed on a component and then dragged.
2. void mouseMoved(MouseEvent e): This method is invoked when a mouse cursor has been
moved onto a component and then dragged.

Program to mouse events demo.


import [Link].*;
import [Link];
import [Link];
public class MouseListenerExample implements MouseListener {
Label lbl1, lbl2;
Frame fr;
String s;
MouseListenerExample() {
fr= new Frame("Java Mouse Listener Example");
lbl1=new Label("Demo for the Mouse Event", [Link]);
lbl2=new Label();
[Link](new FlowLayout());
[Link](lbl1);
[Link](lbl2);
[Link](this);
[Link](250, 250);
[Link](true);
}
public void mouseClicked(MouseEvent ev) {
[Link]("mouse Button clicked");
[Link](true);
}
public void mouseEntered (MouseEvent ev) {
[Link]("Mouse has entered the area of window");
[Link](true);
}
public void mouseExited(MouseEvent ev) {
[Link]("Mouse has left the area of window");
[Link](true);
}
public void mousePressed (MouseEvent ev) {
[Link]("Mouse button is being pressed");
[Link](true);
}
public void mouseReleased (MouseEvent ev) {
[Link](" Mouse Released");
[Link](true);
}
public static void main(String args[]) {
new MouseListenerExample();
}
}

Key Events
A user interacts with an application by pressing keys on the keyboard to enter text, nang or
trigger shortcuts. To handle key events, Java provides the KeyListener interface in the
[Link] package

KeyListener Interface Methods


1. public void keyPressed(KeyEvent ke): This method is called when a key is pressed the
keyboard. It detects both regular keys (A-Z, 0-9) and special keys like Shift. Ctrl. Alt, enter and
function keys.

2. public void keyTyped(keyEvent ke): This method is executed when a key is typed (pressed
released) on the keyboard. Unlike keyPressed(), it detects only printable characters like
letters (A-Z) and numbers (0-9). It does not detect special keys such as Shift, ctrl or function
keys.

[Link] void keyReleased(KeyEvent ke): This method is called when a key is released after
being pressed can be used to perform an action once the user lifts their finger off the key.

Program to demonstrate key events.

import [Link].*;

import [Link].*;

public class KeyListenerExample extends Frame implements KeyListener {

Label lbl;

TextArea ta;

KeyListenerExample() {

lbl = new Label();

[Link](20, 50, 100, 28);

ta = new TextArea();

[Link](28, 88, 300, 200);

[Link](this);

add(lbl);

add(ta);

setSize(400, 350);

setLayout(null);

setVisible(true);

public void keyPressed(KeyEvent e) {

[Link]("Key Pressed");

public void keyReleased(KeyEvent e) {

[Link]("Key Released");

public void keyTyped(KeyEvent e) {


[Link]("Key Typed");

public static void main(String args[]) {

new KeyListenerExample();

GUI

Frames
The Frame is a subclass of Window. It has a border, title bar, and menu bar. A Frame serves
as a container that holds components such as buttons, checkboxes, radio buttons, menus,
lists, tables, and other GUI elements.

Frame is commonly used for building standalone GUI applications in Java. It can be resized,
minimized, maximized, and closed using window controls.

Creating a Frame

import [Link].*;
public class FrameDemo {
FrameDemo() {
Frame fm=new Frame();
[Link]("My First Frame");
Label lb=new Label("Welcome to GUI Programming");
[Link](lb);
[Link](300, 300);
[Link](true);
}
public static void main(String args[]) {
FrameDemo ta = new FrameDemo();
}
}

Panels
Panel is a lightweight container in Java AWT that can hold and organize GUI components
Unlike a Frame, a Panel does not have a title bar, menu bar, or borders. It is primarily used to
group components inside a larger container such as a Frame or a Window

A Panel can serve two purposes:


 As a container → It can hold and organize various GUI components like Buttons,
TextAreas and Checkboxes.
 As a component → It can be added to other containers like Frame Windows and
Dialogs

import [Link].*;
class SamplePanel extends Frame {
SamplePanel() {
setLayout(new FlowLayout());
Panel p1 = new Panel();
Label l1 = new Label("Panel 1 Red");
Button bt1 = new Button("Button 1");
[Link](l1);
[Link](bt1);
[Link]([Link]);
add(p1);
Panel p2 = new Panel();
Label l2 = new Label("Panel 2 Blue");
Button bt2 = new Button("Button 2");
[Link](l2);
[Link](bt2);
[Link]([Link]);
add(p2);
}
}
public class PanelDemo {
public static void main(String[] args) {
SamplePanel fr = new SamplePanel();
[Link]("Panel Example");
[Link](300, 250);
[Link](true);
}
}

Layout Managers:
A Layout Manager in Java is an object that controls the arrangement and positioning of
components within a container. It automatically adjusts the size and layout of components
based on the available space to ensure that the interface adapts to different screen sizes and
resolutions

Syntax:
Void setLayout(LayoutManager layoutObj)

Types of Layout Managers

Java provides several layout managers to control the arrangement of components

1. FlowLayout: It arranges components in a left-to-right flow. It adjusts their positions


based on the container's width.

import [Link].*;
public class FlowLayoutDemo {
FlowLayoutDemo() {
Frame f = new Frame();
Label l1 = new Label("Enter Name:");
TextField t1 = new TextField(10);
Label l2 = new Label("Enter Age:");
TextField t2 = new TextField(10);
Button b1 = new Button("SUBMIT");
[Link](new FlowLayout([Link])); // Right Alignment
[Link](l1);
[Link](t1);
[Link](l2);
[Link](t2);
[Link](b1);
[Link](250, 250);
[Link](true);
}
public static void main(String[] args) {
new FlowLayoutDemo();
}}

[Link]: It divides the container into five regions. These regions are North, South
West, and Center. Each region can hold a single component.

import [Link].*;
public class BorderLayoutDemo {
BorderLayoutDemo() {
Frame frame = new Frame("BorderLayout");
Button b1 = new Button("NORTH");
Button b2 = new Button("SOUTH");
Button b3 = new Button("EAST");
Button b4 = new Button("WEST");
Button b5 = new Button("MIDDLE");
[Link](new BorderLayout());
[Link](b1, [Link])
[Link](b2, [Link]);
[Link](b3, [Link]);
[Link](b4, [Link]);
[Link](b5, [Link]);
[Link](250, 250);
[Link](true);
}
public static void main(String args[]) {
new BorderLayoutDemo();
}
}
3. GridLayout: It organizes components in a grid with equal-sized rows and columns
uniform spacing between components. It is commonly used for creating tables, forms or
button layouts where alignment is crucial.

import [Link].*;
public class GridDemo {
GridDemo() {
Frame frame = new Frame("GridLayoutDemo");
Button b1 = new Button("A");
Button b2 = new Button("B");
Button b3= new Button("C");
Button b4 = new Button("D");
Button b5= new Button("E");
Button b6 new Button("F");
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b4);
[Link](b5);
[Link](b6);
[Link](new GridLayout(2, 3));
[Link](200, 200);
[Link](true);
}
public static void main(String args[]) {
new GridDemo();
}
}

Buttons
A Button in Java AWT is a clickable component used to perform an action when the user
interacts with it. Buttons are commonly used to submit forms, trigger events, or perform
specific tasks in a graphical user interface (GUI). A button displays a label (text) that
describes its function. A button generates events, which can be handled using an
ActionListener.
Program to demonstrate button
import [Link].*;
public class ButtonDemo1 {
public static void main(String[] args) {
Frame f1 = new Frame("Button Demo");
Button b1 = new Button("Press Here");
[Link] (50, 100, 80, 50);
[Link](b1);
[Link](200, 200);
[Link](null);
[Link](true);
}
}

Checkboxes
A CheckBox in Java AWT is a toggle button that allows users to select or deselect an option in
a graphical user interface (GUI). It is commonly used in forms, preference settings, and
multiple-choice selections, where users can choose one or more options. A checkbox has
two states: checked (selected) or unchecked (deselected). Its state can be changed by the
user or modified programmatically

Program to demonstrate checkboxes


import [Link].*;
public class CheckboxDemo {
CheckboxDemo() {
Frame f = new Frame("Checkbox Demo");
Checkbox ckbox1 =new Checkbox("Yes", true);
[Link] (100, 100, 60, 60);
Checkbox ckbox2 = new Checkbox("No");
[Link] (100, 150, 60, 60);
[Link](ckbox1);
[Link](ckbox2);
[Link](300, 300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new CheckboxDemo();
}
}
Radio Buttons
A Radio Button in Java AWT is a type of toggle button that allows users to select only one
option from a group of choices in a graphical user interface (GUI). It is commonly used in
forms, surveys, and option selection menus, where users must choose a single option from
multiple choices.
Unlike a standard CheckBox, a radio button is part of a group and ensures that only one
button in the group can be selected at a time. In Java AWT, radio buttons are implemented
using Checkbox components inside a CheckboxGroup.

Program to demonstrate checkboxes


import [Link].*;
public class CheckboxGroupDemo {
CheckboxGroupDemo() {
Frame fr = new Frame("RadioButton Demo");
CheckboxGroupDemo cbg=new CheckboxGroupDemo();
Checkbox ckbox1 =new Checkbox("java",cbg, true);
[Link] (100, 100, 60, 60);
Checkbox ckbox2 = new Checkbox("No",cbg,false);
[Link] (100, 150, 60, 60);
[Link](ckbox1);
[Link](ckbox2);
[Link](300, 300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new CheckboxGroupDemo();
}
}

Label
A Label in Java AWT is a non-editable text component used to display static text in a
graphical user interface (GUI). It is commonly used to provide instructions, descriptions, or
headings for other components such as text fields, buttons, or checkboxes. A label cannot be
modified by the user. It is used only for displaying information. Labels improve the clarity
and readability of an interface.

Program to demonstrate Label


import [Link].*;
public class LabelDemo {
public static void main(String args[]) {
Frame fr = new Frame("Label Demo");
Label lab1, lab2 lab3;
lab1 = new Label("Java Programming", [Link]);
[Link] (50, 50, 200, 30);
lab2 =new Label("Database Management Systems");
[Link](50, 100, 200, 30);
lab3= new Label("Computer Architecture", [Link]);
[Link](50, 150, 200, 30);
[Link](lab1);
[Link](lab2);
[Link](lab3);
[Link](300, 300);
[Link](null);
[Link](true);
}
}

TextField
A TextField in Java AWT is an editable text component that allows users to enter and modify
a single line of text in a graphical user interface (GUI). It is commonly used in forms, login
screens, search bars, and input fields where users need to provide textual input. A text field
can have a default value, and its content can be modified programmatically.

Program to demonstrate TextField


import [Link].*;
public class TextFieldDemo {
public static void main(String args[]) {
Frame fr =new Frame("TextField Demo");
TextField text1, text2;
text1= new TextField("Enter Your Name...");
[Link] (60, 100, 150, 40);
text2 = new TextField("Enter Your Age ...");
[Link] (60, 150, 150, 40);
[Link](text1);
[Link](text2);
[Link](250, 250);
[Link](null);
[Link](true);
}
}

TextArea
A TextArea in Java AWT is an editable text component that allows users to enter and modify
multiple lines of text in a graphical user interface (GUI). It is commonly used in feedback
forms, chat applications, text editors, and document processing where users need to input
or display large amounts of text.

Program to demonstrate TextArea

import [Link].*;
public class TextAreaDemo {
TextAreaDemo() {
Frame fr new Frame();
TextArea ta= new TextArea ("Type Here");
[Link](30, 40, 100, 100);
[Link](area);
[Link](250, 250);
[Link](null);
[Link](true);
public static void main(String args[]) {
new TextAreaDemo();
}
Combo Box(Choice)

A ComboBox in Java AWT, known as a Choice component, is a drop-down list. It allows users
to select one option from multiple choices. It is commonly used in forms, selection menus,
and configuration settings. Users must choose a single option from a predefined list. A
combo box does not require multiple visible options. It presents a drop-down menu that
appears when the user clicks on it. This saves space and improves usability.

The difference between a ComboBox (Choice) and a Radio Button is how they display
options. Radio buttons show all options at once. A combo box displays only the selected
option until the user clicks to open the list.

Program to demonstrate TextArea

import [Link].*;
public class ChoiceDemo {
ChoiceDemo() {
Frame fr = new Frame();
Choice ch = new Choice();
[Link] (80, 80, 100, 100);
[Link]("BCA");
[Link]("BCom");
[Link]("BBA");
[Link]("BA");
[Link]("BHM");
[Link]("BSc");
[Link](ch);
[Link](300, 300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new ChoiceDemo();
}
}
List
List in Java AWT is a component that displays a list of items. Users can select one or multiple
options from the list. It is commonly used in forms, data selection menus, and multi-choice
options. It helps users pick items from a predefined list. A List provides a scrollable list of
choices. A ComboBox (Choice), on the other hand, displays a drop-down menu.

The difference between a List and a ComboBox (Choice) is how they display options. A
ComboBox (Choice) shows only one selected item until the user clicks to open the drop-
down. A List displays multiple items at once. Users can scroll through the list to view all
available options.

Program to Demonstrate List

import [Link].*;
public class ListDemo {
ListDemo() {
Frame fr =new Frame("List Demo");
List lst = new List(6, true);
[Link] (80, 80, 100, 100);
[Link]("C");
[Link]("C++");
[Link]("Java");
[Link]("Python");
[Link]("C#");
[Link]("PHP");
[Link](1st);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new ListDemo();
}
}
Scroll bars
A Scrollbar in Java AWT is a component that allows users to scroll content vertically or
horizontally. It is used when the content is larger than the visible area. Scrollbars help users
navigate through text, images, or other elements that do not fit within the displayed space.
They are commonly used in windows, panels, and text areas.

Program to Demonstrate Scrollbar

import [Link].*;
public class ScrollbarExample {
ScrollbarExample() {
Frame f = new Frame("Scrollbar Example");
Scrollbar s = new Scrollbar();
[Link](100, 100, 50, 100);
[Link](s);
[Link](300, 300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new ScrollbarExample();
}
}

Slider
A Slider in Java AWT is a component that allows users to select a value from a defined range
by moving a slider knob. It is commonly used in applications where users need to adjust
values, such as volume control, brightness adjustment, and zoom levels.

The difference between a Scrollbar and a Slider is their purpose. A Scrollbar is mainly used
for navigation. It helps users scroll through content that is not fully visible. A Slider is used to
select a value from a range, such as adjusting volume or brightness.

Syntax:
Scrollbar(int orientation, int value, int visible, int min, int max);
Program to Demonstrate Scrollbar

import [Link].*;
public class ScrollbarExample {
ScrollbarExample() {
Frame f = new Frame("Scrollbar Example");
Scrollbar s = new Scrollbar
([Link], 50, 1, 0, 101);
[Link] (50, 150, 200, 30);
[Link](s);
[Link](300, 300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new ScrollbarExample();
}
}

Menus
A Menu in Java AWT is a component that allows users to navigate through options in a
structured way. Menus are commonly used in desktop applications. They provide a drop-
down list of commands. The Menu class is a pull-down menu component. It appears on a
MenuBar. Each menu can contain Menultem objects. These objects represent individual
options.
In Java AWT, the Menu, MenuBar, and Menultem classes are used together to create a
structured menu system.

 The MenuBar class represents the top-level menu container that holds multiple
menus.
 The Menu class represents a drop-down menu that appears when the user clicks on
it in the menu bar.
 The Menultem class represents individual options inside a menu that users can
select.
Each Menu must be added to a MenuBar, and each Menultem must be added to a Menu.

Program to Demonstrate MenuBar, Menu and MenuItem

import [Link].*;
public class MenuDemo {
MenuDemo() {
Frame fr = new Frame("Menu Demo");
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu("View");
[Link](fileMenu);
[Link](editMenu);
[Link](viewMenu);
MenuItem a1 = new MenuItem("New");
MenuItem a2 = new MenuItem("Open");
MenuItem a3 = new MenuItem("Save");
MenuItem b1 = new MenuItem("Copy");
MenuItem b2 = new MenuItem("Find");
MenuItem c1 = new MenuItem("Show");
[Link](a1);
[Link](a2);
[Link](a3);
[Link](b1);
[Link](b2);
[Link](c1);
[Link](mb);
[Link](300, 300);
[Link](null);
[Link](true);
}
public static void main(String args[]) {
new MenuDemo();
}
}

Dialog box
A Dialog in Java AWT is a pop-up window that appears on top of the main application
window. It is a type of window which is having a border and a title. But it does not have any
maximize and minimize button. It is used to display messages, take user input, or provide
notifications. It is commonly used for alerts, confirmations, and input forms.

Types of Dialog Window


Is java AWT, dialogs are pop-up windows that appear on top of the main application window.
They are used for displaying messages, taking user input, or showing alerts. There are two
types of dialog windows: Modal Dialog and Non-Modal Dialog.
The key difference between them is whether they allow interaction with the main
application while the dialog is open.
1. Modal Dialog Window
A Modal Dialog blocks interaction with the main application window until it is closed. When
a modal dialog is active, the user must complete an action in the dialog before returning to
the main window. This type of dialog is used when an immediate response is required from
the user

Example:
A "Save Changes" confirmation dialog appears before closing a document. The user must
click "Save", "Don't Save", or "Cancel" before continuing.

2. Non-Modal Dialog
A Non-Modal Dialog allows the user to interact with both the dialog and the main
application at the same time. The user does not need to close the dialog before using other
parts of the application. This type of dialog is useful for tools or settings that remain open
while users work.

Example:
A "Find and Replace" dialog in a text editor allows users to search for words while continuing
to edit the document.

Note: Both types of dialog windows help improve user interaction. Modal dialogs are used
when immediate attention is required. Modeless dialogs are used when users need
additional tools while working in the main application.

Program to Demonstrate Both Modal and Non-Modal Dialogs

import [Link].*;
import [Link].*;
public class DialogExample {
DialogExample() {
Frame f = new Frame("Dialog Demo");
[Link](350, 200);
[Link](new FlowLayout());
// TextField to test interaction during Non-Modal Dialog
TextField tf=new TextField(20);
[Link](new Label("Try typing here:"));
[Link](tf);
// Button to open Modal Dialog
Button modalBtn=new Button("Open Modal Dialog");
[Link](e -> {
Dialog modalDialog =new Dialog(f, "Modal Dialog", true);
[Link](new FlowLayout());
[Link](new Label("This is a Modal Dialog"));
Button closeBtn=new Button(“Close”);
[Link](ae -> [Link](false));
[Link](closeBtn);
[Link](250, 150);
[Link](true);
});

// Button to open Non-Modal Dialog


Button nonModalBtn = new Button("Open Non-Modal Dialog");
[Link](e -> {
Dialog nonModalDialog =new Dialog(f, "Non-Modal Dialog", false);
[Link](new FlowLayout());
[Link](new Label("This is a Non-Modal Dialog"));
Button closeBtn = new Button("Close");
[Link](ae -> [Link](false));
[Link](closeBtn);
[Link](250, 150);
[Link](true);
});
[Link](modalBtn);
[Link](nonModalBtn);
[Link](true);
}
public static void main(String[] args) {
new DialogExample();
}
}

(OR)

import [Link].*;
import [Link].*;
public class AWTDialogExample {
public static void main(String[] args) {
Frame frame = new Frame("AWT Dialog Example");

// Button to show dialog


Button showDialogButton = new Button("Show Dialog");
[Link](50, 100, 100, 30);
[Link](showDialogButton);
[Link](300, 200);
[Link](null);
[Link](true);

// Dialog setup
Dialog dialog = new Dialog(frame, "This is a dialog", true);
[Link](new FlowLayout());
[Link](200, 150);
Label msg = new Label("Hello from AWT Dialog!");
Button okButton = new Button("OK");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link](false);
}
});
[Link](msg);
[Link](okButton);

// Show dialog on button click


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link](true);
}
});

// Close main frame properly


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link]();
}
});
}
}

Applet Programming

What is an Applet?
An Applet is a small Java program that runs inside a web browser or an applet viewer. Unlike
standalone applications, applets do not have a main() method. Instead, they rely on the web
browser. or applet viewer to control their execution. We think of an applet as:
Applet =Java Byte Code + HTML

(OR)

An applet is a Java-based program that runs within a browser as part of a web page. It is
downloaded from a remote server and executed on the client's machine using the browser's
applet engine. Applets are mainly used in web applications where user interaction is
required, such as online games, calculators, charts, and form validations.

What are Local and Remote Applets?

->A local applet is an applet that is developed and executed on the same computer. It does
not require an internet or network connection to run.

->A remote applet is developed by someone else and is stored on a remote machine
(server). To load and execute a remote applet, an internet or network connection is required

Comparision of Applets and Applications

Applets Applications

1. Applets do not have main() for 1. Applications have main() for initiating
initiating the execution of code. the execution of the code.
2. Applets cannot be executed 2. Applications are programs that can be
independently. They are executed within executed independently.
a java browser or using appletviewer.
3. Applets don’t have local disk and 3. Java application programs have the full
network access. access to the local file system and
network.
4. Applets can be embedded into HTML 4. Applications cannot be embedded into
page. HTML page.

5. Applets cannot communicate with 5. Applications can communicate with


other servers in the network. other servers.
6. Applets cannot use libraries from other 6. Applications can use libraries from
languages. other languages.

Applet Life Cycle

Applets are designed to pass through various stages of its lifecycle as shown below:
Lifecycle Methods of an Applet

An applet has four main lifecycle methods:


1. init(): This method is called first when the applet is loaded.
2. start(): This method is called after init() and when the applet becomes active.
3. stop(): This method is called when the applet is temporarily suspended.
4. destroy(): This method is called when the applet is removed from memory

These methods are called automatically by the applet engine. The init() and destroy()
methods called only once during the entire lifetime of an applet. However, the start() and
stop() methods can be called multiple times.

1. init() Method
The init() method is the first method called when an applet is loaded in a browser. It is used
for initializing the applet. This method is useful for setting up the user interface, loading
images, or initializing variables. The init() method is executed only once in the applet's
lifecycle, Once this method completes, the browser automatically calls the start() method.

public void init() {

// Initialization code goes here


}

2. start() Method
The start() method is called after the init() method. It is used to define the starting behavior
of the applet. This method is called whenever the applet becomes active. If the user
navigates away from the web page containing the applet and then returns, the start()
method is called again
public void start() {

// Code to start execution


}

3. stop() Method
The stop() method is called when the applet is temporarily suspended. If the user moves to
another web page or minimizes the browser, the applet enters the stopped state. When the
user returns to the web page, the start() method is called again. The stop() method is used
to pause animations or release temporary resources.

public void stop() {

// Code to stop execution

4. destroy() Method

The destroy() method is called when an applet is being removed from memory. This usually
happens when the browser is closed or the user leaves the web page permanently.

public void destroy() {

// Code to release resources

}
[Link]() Method
is not part of the applet's lifecycle, but it is essential for displaying output. This method is
called when the applet needs to draw something on the screen. It is automatically invoked
after the start() method. The paint() method is commonly used to display text, images,
shapes, and other graphical elements.

public void paint(Graphics g) {

// Drawing code goes here

Important Note

The paint() method takes a Graphics object as a parameter. This object is automatically
created by the browser and passed to the method. To use the Graphics class, we must
import the [Link] package at the beginning of the program:
import [Link];
Developing and Running Applets By Creating Separate HTML File.
Step 1: Writing Applet Code

import java . applet . Applet;


import java .[Link];
public class MyFirstApplet extends Applet
{
public void paint(Graphics g)
{
[Link](“Hello Applet”,20,30);
}
}

Step 2: Create a HTML page

<HTML>
<Head>
<Title>This is my first Applet</Title>
</Head>
<Body>
<Applet code=[Link] width=400 height=500>
</Applet>
</Body>
</HTML>

Developing and Executing An Applet Without HTML

JAVA PROGRAM TO IMPLEMENT THE LIFE CYCLE OF THE APPLET.

import [Link];
import [Link];
/*
<applet Code="AppletLifeCycle" width=500 height=500>
</applet>
*/
public class AppletLifeCycle extends Applet
{
public void init()
{
[Link]("Applet Initialized");
}
public void start()
{
[Link]("Applet Started");
}
public void stop()
{
[Link]("Applet Stopped");
}
public void destroy()
{
[Link]("Applet Destroyed");
}
public void paint(Graphics g)
{
[Link]("Applet Life cycle",50,100);
}
}
Advantages and Disadvantages of Applets

Advantages of Applet
 Applets run inside a web browser and do not require separate installation.
 They provide a secure execution environment with restricted access to system
resources.
 Applets are platform-independent and run on any system with a Java-enabled
browser
 They support rich graphics and user interaction for web-based applications.
 Applets can be easily embedded into HTML pages using the <APPLET> tag

Disadvantages of Applet
 They require Java plugin support, which is no longer available in modern web
browsers.
 Applets have limited access to system resources due to security restrictions.
 They depend on the web browser's Java support, which varies across different
browsers.
 Its difficult to design and build good user interface in applets compared to other
technologies.
 Applets load slower than standalone applications because they require network
access

You might also like