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

java applet_1

Java Applets are embedded programs that run in web browsers, providing dynamic content with advantages like reduced response time and cross-platform compatibility, though they require a plugin to execute. The applet lifecycle includes initialization, starting, painting, stopping, and destruction, with specific methods for each stage. Event handling in applets uses the Delegation Event Model, allowing separation of event generation and handling, with listeners responding to user actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java applet_1

Java Applets are embedded programs that run in web browsers, providing dynamic content with advantages like reduced response time and cross-platform compatibility, though they require a plugin to execute. The applet lifecycle includes initialization, starting, painting, stopping, and destruction, with specific methods for each stage. Event handling in applets uses the Delegation Event Model, allowing separation of event generation and handling, with listeners responding to user actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and
works at client side.There are many advantages of applet. They are as follows:It works at client side so less response time, Secured, It
can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.Drawback of Applet are the
Plugin is required at client browser to execute applet.

 Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started. Applet is
initialized
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed. The Applet is Applet is
destroyed started
Life
Cycle
java.applet.Applet class 4 life cycle
Applet
methods and java.awt.Component class
provides 1 life cycle methods for an
applet.For creating any applet Applet is Applet is
stopped painted
java.applet.Applet class must be inherited. It
provides 4 life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

The Component class provides 1 life cycle method of applet.

5. 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.

There are two ways to run an applet: 1.By html file.2.By applet Viewer tool (for testing purpose).

Example of Applet by html file:To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){

g.drawString("welcome",150,150);

} }

Output:myapplet.html

<html>

<body>

<applet code="First.class" width="300" height="300">

</applet>

</body>

</html>
 Parameter passing in applets: Java allows users to pass user-defined parameters to an applet with the help of
<PARAM>tags. The <PARAM>tag has a NAME attribute which defines the name of the parameter and a VALUE attribute
which specifies the value of the parameter. In the applet source code, the applet can refer to the parameter by its NAME to
find its value. The syntax of the <PARAM>tag is :< APPLET>
<PARAMNAME=parameter1_name VALUE=parameter1_value>
<PARAMNAME=parameter2_name VALUE=parameter2_value>
<PARAMNAME=parametern_name VALUE=parametern_value>
</APPLET>
For example, consider the following statements to set the text attribute of applet to This is an example of Parameter! ! !
<APPLET>

<PARAMNAME=text VALUE=This is an example of Parameter!!!>

</APPLET>

Note that the <PARAM>tags must be included between the <APPLET> and</ APPLET> tags. The init () method in the applet
retrieves user-defined values of the parameters defined in the <PARAM>tags by using the get Parameter () method. This method
accepts one string argument that holds the name of the parameter and returns a string which contains the value of that parameter. Since
it returns String object, any data type other than String must be converted into its corresponding data type before it can be used.

import java.awt.*;

import java.applet.*;

<applet code="ParamApplet" width=300 height=80>

<paramname=fontName value=Courier>

<param name=fontSize value=14>

<param name=leading value=2>

<param name=accountEnabled value=true>

</applet>

*/public class ParamApplet extends Applet

{ String name;

int size;

float lead;

boolean active;

public void start()

{String pa;

name = getParameter("Name");

if(name == null)
name = "Not Found";

pa = getParameter("Size");

try

{ if(pa != null)

size = Integer.parseInt(pa);else size = 0;

catch(NumberFormatException e)

{size = -1; }

pa = getParameter("lead");

try

{ if(pa != null)

lead = Float.valueOf(pa).floatValue();

else

lead = 0;

catch(NumberFormatException e)

lead = -1;

pa = getParameter("AccountEnabled");

if(pa != null)

active = Boolean.valueOf(pa).booleanValue();

public void paint (Graphics g)

g.drawString("Name: " + name, 0, 10);

g.drawString("Size: " + size, 0, 26);

g.drawString("Leading: " + lead, 0, 42);


g.drawString("Account Active: " + active, 0, 58);

Output:

 Event Handling:Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism have the code which is known as event handler that is executed when 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.

The Delegation Event Model has the following key participants namely:

1. 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.

2. 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 a then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user
interface element is able to delegate the processing of an event to the separate piece of code. In this model, Listener needs to be
registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event
because the event notifications are sent only to those listener that want to receive them.

 Steps involved in event handling:


1. The User clicks the button and the event is generated.
2. Now the object of concerned event class is created automatically and information about the source and the event get
populated with in same object.
3. Event object is forwarded to the method of registered listener class.
4.the method is now get executed and returns.

In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some public abstract
callback methods which must be implemented by the listener class. If you do not implement the any if the predefined interfaces then
your class can not act as a listener class for a source object.

 Callback Methods: These are the methods that are provided by API provider and are defined by the application programmer
and invoked by the application developer. Here the callback methods represents an event method. In response to an event
java jre will fire callback method. All such callback methods are provided in listener interfaces. If a component wants some
listener will listen to it's events the the source must register itself to the listener.
Event Handling Example:Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint
> gui >

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showEventDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showEventDemo(){


headerLabel.setText("Control in action: Button");

Button okButton = new Button("OK");


Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");

okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);

mainFrame.setVisible(true);
}

private class ButtonClickListener implements ActionListener{


public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button clicked.");
}
else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
}
else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.: D:\AWT>javac com\
tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command:D:\AWT>java com.tutorial
spoint.gui.AwtControlDemo

Output:
 GetCodeBase and GetDocumentBase: You will create applets that will need to explicitly load media and text. Java will
allow the applet to load data from the directory holding the html file that started the applet (the document base) and the
directory from which the applet’s class file was loaded (the code base). These directories are returned by
getDocumentBase( ) and getCodeBase( ).

Program:

import java.applet.Applet;

import java.awt.Graphics;

public class Javaapp extends Applet{

public void paint(Graphics g)

{ g.drawString("getCodeBase : "+getCodeBase(), 20, 20);

g.drawString("getDocumentBase : "+getDocumentBase(), 20, 40);

}}

 Paint() and Repaint() method:


paint(): This method holds instructions to paint this component. In Java Swing, we can change the paintComponent() method
instead of paint() method as paint calls paintBorder(), paintComponent() and paintChildren() methods. We cannot call this
method directly instead we can call repaint().
repaint(): This method cannot be overridden. It controls the update() -> paint() cycle. We can call this method to get a
component to repaint itself. If we have done anything to change the look of the component but not the size then we can call
this method.

Program:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

public class PaintRepaintTest extends JPanel implements MouseListener {

private Vector v;

public PaintRepaintTest() {

v = new Vector();

setBackground(Color.white);

addMouseListener(this);

}
public void paint(Graphics g) { // paint() method

super.paint(g);

g.setColor(Color.black);

Enumeration enumeration = v.elements();

while(enumeration.hasMoreElements()) {

Point p = (Point)(enumeration.nextElement());

g.drawRect(p.x-20, p.y-20, 40, 40);

public void mousePressed(MouseEvent me) {

v.add(me.getPoint());

repaint(); // call repaint() method

public void mouseClicked(MouseEvent me) {}

public void mouseEntered(MouseEvent me) {}

public void mouseExited(MouseEvent me) {}

public void mouseReleased(MouseEvent me) {}

public static void main(String args[]) {

JFrame frame = new JFrame();

frame.getContentPane().add(new PaintRepaintTest());

frame.setTitle("PaintRepaint Test");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setSize(375, 250);

frame.setVisible(true);

Output:

You might also like