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

Applet New

Applet is a small Java program designed to be embedded in HTML pages and executed in web browsers, providing a secure way to run applications with limited resource access. The document outlines the differences between applications and applets, the benefits of applets, the steps to create them, their lifecycle, and the event handling mechanism in Java. It also includes examples of applet code for various functionalities such as displaying images, handling user input, and creating animations.

Uploaded by

sharmayashikagzb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Applet New

Applet is a small Java program designed to be embedded in HTML pages and executed in web browsers, providing a secure way to run applications with limited resource access. The document outlines the differences between applications and applets, the benefits of applets, the steps to create them, their lifecycle, and the event handling mechanism in Java. It also includes examples of applet code for various functionalities such as displaying images, handling user input, and creating animations.

Uploaded by

sharmayashikagzb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Applet

Basics of Applet

 Applets are small Internet-based program written in Java, a


programming language for the Web and can be downloaded by any
computer. The applet is also capable of running in HTML. The applet
is usually embedded in an HTML page on a Web site and can
be executed from within a browser.
 After an applet arrives on the client, it has limited access to resources
so that it can produce a graphical user interface and run complex
computations without introducing the risks of viruses or data security
breaching.
Application vs. Applet
Application Applet
Applets are small Java programs
Applications are stand-alone
that are designed to be included
programs that can be run
in a HTML web document. They
independently without having to
require a Java-enabled browser for
use a web browser.
execution.
Java applications have full access Applets have no disk and
to local file system and network. network access.
It requires a main method() for its It does not require a main
execution. method() for its execution.
Applications can run programs from Applets cannot run programs from
the local system. the local machine.
An application program is used to
An applet program is used to
perform some task directly for the
perform small tasks or part of it.
user.
It can access all kinds of resources It can only access the browser
Benefits of Applet
 They are very secure.
 It works at client side so less response time.
 Applets can be executed by browsers running under different
platforms.
 One disadvantage of Applets is that plugins are required at
the client browser for executing applets.
Creating applet

 Steps involved in developing and testing in applet are:


1. Building an applet code (.java file)
2. Creating an executable applet (.class file)
3. Designing a web page using HTML tags.
4. Preparing <applet> tag
5. Incorporate <apple> tag into the web page.
6. Creating HTML file
7. Testing the applet code.
1. Building an applet code (.java file)

2. Creating an executable applet

To compile : C:\> javac SimpleApplet.java


3.Designing a we page using HTML tags.
<html>
<head>
<TITLE> A Simple Program </TITLE> </head>
<body> Here is the output of my program:
<applet code=“SimpleApplet.class" width="150" height="25"> (4. Preparing <applet>
tag)
(5. Incorporate <apple> tag into the web page)
</applet> </body> </html>

Save as a.html (6. Creating HTML file)


To Execute: C:\\ appletviewer a.html
(7. Testing the applet code.)
Hierarchy of Applet
Package required for an Applet
 java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
 java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
Applet life cycle
 Initialization State: Applet enters initialization state when it is loaded. This is achieved
by calling the init() method of Applet class. The applet is born. At this stage, we may do the
following, if required.
1. Create objects needed by the applet
2. Set up initial values
3. Load images or fonts
4. Set up colors
This method is called only once during the run time of your applet. To provide any of the behaviors
mentioned above we must override the init() method.
public void init()
{ . . . . .(Action)
}
 Running State: Applet enters the running state when the system calls the start() method
of Applet class. The start( ) method is called after init( ). It is also called to restart an applet after
it has been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded
whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So,
if a user leaves a web page and comes back, the applet resumes execution at start( ).we
may override the start() method to create a thread to control the applet.
public void start()
{ . . . . .(Action)
}
 Idle or Stopped State: An applet becomes idle when it is stopped from running.
Stopping occurs automatically when we leave the page containing the currently running
applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the
applet, then we must use stop() method to determine the thread. We can achieve this by
overriding the stop() method
public void stop()
{ . . . . .(Action)
}
 Dead State: An applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when we quit the browser. Like
initialization destroying stage occurs only once in the applet’s life cycle. If the applet has created
any resources like threads, we may override the destroy() method to clean up these resources.
public void destroy()
{ . . . . .(Action)
}
 Display State: Applet moves to the display state whenever it has to perform some output
operations on the screen. This happens immediately after the applet enters into the running state.
The paint() method is called to accomplish this task. If we want to display any thing on screen we
need to override paint() method.
public void paint(Graphics g)
{ . . . . .(Action)
}
Local applet Vs Remote applet
 Local Applet:- An applet developed locally and stored in a local system is known as a
local applet. When a Web page is trying to find a local applet, it does not need to use the
Internet and therefore the local system does not require the Internet connection. It simply
searches the directories in the local system and locates and loads the specified applet.
 Specifying a Local Applet:
<applet codebase="path" code="NewApplet.class" width=120 height=120
></applet>

 Remote Applets:- A remote applet is developed by someone else and stored on a remote
computer connected to the Internet. If our system is connected to the internet, we can
download the remote applet onto our system via at the Internet and run it. To locate and
load a remote applet, we must know the applet’s address on the Web. This address is
known as Uniform Resource Locator (URL) and must be specified in the applet’s HTML
document as the value of the CODEBASE attribute.
 Specifying a Remote Applet:
<applet
codebase=http://www.myconnectdemo.com/applets/code="NewApplet.class"
width=120 height=120> </applet>
Attributes of <applet>
tags
ATTRIBUTE NAME VALUES REMARKS
left
right
top
align Specifies the alignment of an applet.
bottom
middle
baseline
alt text Specifies an alternate text for an applet
archive URL Specifies the location of an archive file
Specifies the border around the applet
border pixels
panel
Specifies a relative base URL for applets
codebase URL
specified in the code attribute
height pixels Specifies the height of an applet
Defines the horizontal spacing around an
hspace pixels
applet
Defines the name for an applet (to use in
name name
scripts)
Defines the vertical spacing around an
vspace pixels
applet
Parameter in Applet
 We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter(). Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:

import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
} //UseParam.java file
myapplet.html

<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Display numerical value in applet
import java.awt.*;
import java.applet.*;
public class DisplayNumericalValues extends Applet
{
public void paint(Graphics g)
{
int val1 = 10;
int val2 = 20;
int sum = val1 + val2;
String str_sum = "Sum="+String.valueOf(sum);
g.drawString(str_sum,100,200);
}
} // DisplayNumericalValues.java file
Html file

<HTML>
<HEAD>
<TITLE>Display Numerical Values</TITLE>
</HEAD>
<BODY>
<APPLET Code="DisplayNumericalValues.class“
Width=400 Height=300>
</APPLET>
<BODY>
</HTML>
Getting Input from User
import java.awt.*;
import java.applet.*;
public class textFieldDemo extends Applet
{ String str;
int a,b,result;
TextField t1,t2; //Creating Object of TextField Class
public void init()
{ t1=new TextField(10);
t2=new TextField(10);
add(t1);
add(t2);
t1.setText("0");
t2.setText("0"); }
public void paint(Graphics g)
{ str=t1.getText();
a=Integer.parseInt(str);
str=t2.getText();
b=Integer.parseInt(str);
result=a+b;
str=String.valueOf(result);
Html File

<html>
<body>
<applet code="textFieldDemo.class" width="300"
height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Commonly used methods of Graphics class:

 public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
 public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
 public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
 public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
 public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
 public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
 public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
Commonly used methods of Graphics class:

 public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
 public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
 public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
 public abstract void setFont(Font font): is used to set the graphics current font to
the specified font.
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} } //GraphicsDemo.java file
Html file

<html>
<body>
<applet code="GraphicsDemo.class" width="300"
height="300">
</applet>
</body>
</html>
Example of displaying image in
applet:
import java.awt.*;
import java.applet.*;
/* <html>
<applet code="DisplayImage.class" width="300" height="300">
</html>*/
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg"); }
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this); } }
Animation in Applet
import java.awt.*;
import java.applet.*;
/* <html> <body>
<applet code=“AnimationExample.class" width="300" height="300">
</applet> </body> </html> */
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif"); }
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}
catch(Exception e){} } } }
Event
 Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user
interface components.
 Types of Event: The events can be broadly classified into two categories:
1. Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page etc.
2. Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.
Event handling
 Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs.
 Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events. Let's have a brief introduction to this model.
Its concept is quite simple:
 A source generates an event and sends it to one or more listeners. In this scheme, the listener
simply waits until it receives an event.
 Once received, the listener processes the event and then returns.

 The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
 Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event an then
returns.
The benefit of this approach is that the user interface logic is completely separated
The Delegation Event Model
Contd….
 Inthe delegation event model, listeners must
register with a source in order to receive an event
notification. This provides an important benefit:
notifications are sent only to listeners that want to
receive them.
 Events : In the delegation model, an event is an
object that describes a state change in a source. It
can be generated as a consequence of a person
interacting with the elements in a graphical user
interface.
Event Sources
A source is an object that generates an event. This
occurs when the internal state of that object
changes in some way. Sources may generate more
than one type of event.
public void addTypeListener(TypeListener el)
 Here,Type is the name of the event and el is a
reference to the event listener. For example,
 The method that registers a keyboard event listener
is called addKeyListener( ).
 The method that registers a mouse motion listener
is called addMouseMotionListener( ).
 A source must also provide a method that allows a listener to
unregister an interest in a specific type of event. The general
form of such a method is this:
public void removeTypeListener(TypeListener el)

Event Listeners

 A listener is an object that is notified when an event occurs. It


has two major requirements.
 First, it must have been registered with one or more sources to
receive notifications about specific types of events.
 Second, it must implement methods to receive and
process these notifications.
Steps involved in event handling

 The User clicks the button and the event is generated.


 Now the object of concerned event class is created automatically and
information about the source and the event get populated with in
same object.
 Event object is forwarded to the method of registered listener class.
 the method is now get executed and returns.
Sources of Events
Event Listener Interfaces
Event Listener

 Methods in Interfaces:
 ActionListener
void actionPerformed (ActionEvent ae)
 AdjustmentListener
void adjustmentValueChanged (AdjustmentEvent ae)
 ComponentListener
void componentResized (ComponentEvent ce)
void componentMoved (ComponentEvent ce)
void componentShown (ComponentEvent ce)
void componentHidden (ComponentEvent ce)
 ContainerListener
void componentAdded (ContainerEvent ce)
void componentRemoved (ContainerEvent ce)
 FocusListener
void focusGained (FocusEvent fe)
void focusLost (FocusEvent fe)
 ItemListener: void itemStateChanged (ItemEvent ie)
 KeyListener: void keyPressed (KeyEvent ke)
void keyReleased (KeyEvent ke)
void keyTyped (KeyEvent ke)
 MouseListener: void mouseClicked (MouseEvent me)
void mouseEntered (MouseEvent me)
void mouseExited (MouseEvent me)
void mousePressed (MouseEvent me)
void mouseReleased (MouseEvent me)
 MouseMotionListener: void mouseDragged (MouseEvent me)
void mouseMoved (MouseEvent me)
 TextListener: void textChanged (TextEvent te)
 WindowListener: void windowActivated (WindowEvent we)
void windowClosed (WindowEvent we)
void windowClosing (WindowEvent we)
void windowDeactivated (WindowEvent we)
void windowDeiconified (WindowEvent we)
void windowIconified (WindowEvent we)
Handling Keyboard Events
 To handle keyboard events, you use the same general
architecture as that shown in the mouse event example in the
preceding section. The difference, of course, is that you will be
implementing the KeyListener interface.
 Before looking at an example, it is useful to review how key
events are generated.
 When a key is pressed, a KEY_PRESSED event is generated.
This results in a call to the keyPressed( ) event handler.
When the key is released, a KEY_RELEASED event is
generated and the keyReleased( ) handler is executed. If a
character is generated by the keystroke, then a KEY_TYPED
event is sent and the keyTyped( ) handler is invoked.
Introduction to AWT Package
 AWT stands for Abstract Window Toolkit. It is a platform
dependent API for creating Graphical User Interface (GUI) for java
programs.
Component
 At the top of the AWT hierarchy is the Component
class. Component is an abstract class that
encapsulates all of the attributes of a visual
component. All user interface elements that are
displayed on the screen and that interact with the
user are subclasses of Component.
 It defines over a hundred public methods that are
responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window,
and repainting
 Component object is responsible for
remembering the current foreground and
background colors and the currently selected text
font.
Container
 The Container class is a subclass of Component. It has
additional methods that allow other Component objects to
be nested within it.
 Other Container objects can be stored inside of a
Container (since they are themselves instances of
Component).

Panel
 The Panel class is a concrete subclass of Container.
It doesn’t add any new methods; it simply
implements Container. A Panel may be thought of as
a recursively nestable, concrete screen component.
 Panel is the superclass for Applet. When screen
output is directed to an applet, it is drawn on the surface
of a Panel object. In essence, a Panel is a window that
does not contain a title bar, menu bar, or border.
Window
 The Window class creates a top-level window. A top-level
window is not contained within any other object; it sits directly
on the desktop.

Frame
 Frame encapsulates what is commonly thought of as a
“window.” It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners.

Canvas
 Although it is not part of the hierarchy for applet or frame
windows, there is one other type of window that you will find
valuable: Canvas.
 Canvas encapsulates a blank window upon which you can
draw.
Useful Methods of Component class
Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the
component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by


default false.
AWT Example
 To create simple awt example, you need a frame. There are two ways
to create a frame in AWT.
 By extending Frame class (inheritance)
 By creating the object of Frame class (association)
AWT Example by Inheritance
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
AWT Example by Association
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
AWT Controls
The AWT supports the following types of controls:
 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text Area
 Text Field
These controls are subclasses of Component.
Adding and Removing Controls: Component add(Component compObj)
void remove(Component
obj)
Labels: Label( ) Label(String str) Label(String str, int how)
void setText(String str) String getText( )
void setAlignment(int how) int getAlignment( )
Buttons: Button( ) Button(String str)
setLabel( ) getLabel( )
Check Boxes: Checkbox( ) Checkbox(String str) Checkbox(String str,
boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
boolean getState( ) void setState(boolean on) String getLabel( ) void
setLabel(String str)
Checkbox Group (Radio Buttons):
Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox wh)
Layout Manager
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is
an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:
 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout
 javax.swing.BoxLayout
 javax.swing.GroupLayout
 javax.swing.ScrollPaneLayout
 javax.swing.SpringLayout etc.
Border Layout

BoxLayout
CardLayout

FlowLayout
GridBagLayout

GridLayout
GroupLayout

SpringLayout
ActionListener Interface

 The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in java.awt.event
package. It has only one method: actionPerformed().

actionPerformed() method: The actionPerformed() method is invoked automatically


whenever you click on the registered component.

 public abstract void actionPerformed(ActionEvent e);


import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}

You might also like