0% found this document useful (0 votes)
56 views15 pages

OOPS - Unit 5

The document discusses Java applets, including their advantages, disadvantages, lifecycle, and how to create simple applets. Key points include applets running at the client-side in the browser, requiring a plugin, and having methods like init(), start(), stop(), and destroy() that correspond to stages in the applet lifecycle. Examples are provided of creating applets that display text, images, and play sounds.
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)
56 views15 pages

OOPS - Unit 5

The document discusses Java applets, including their advantages, disadvantages, lifecycle, and how to create simple applets. Key points include applets running at the client-side in the browser, requiring a plugin, and having methods like init(), start(), stop(), and destroy() that correspond to stages in the applet lifecycle. Examples are provided of creating applets that display text, images, and play sounds.
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/ 15

UNIT 5

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.

Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac
Os etc.

Drawback of Applet
 Plugin is required at client browser to execute applet.

Hierarchy of Applet
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for 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.

5. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object as
parameter that can be used for drawing oval, rectangle, arc, lines etc.

Steps to run an Applet


There are two ways to run an applet

1. By using html file.


2. By using appletviewer.

Simple Applet program..

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);
}
}
>javac First.java

1) To.run in a Browser..

myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
 Now open the html file myapplet.html in browser to view the output..
 Here First.class is an applet program compiled by java which is executed from within a browser using
html tag.

2) By using appletViewer tool

The below mentioned applet tag, will be a part of First.java file and is compiled(ie javac
First.class) to generate class file.
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

Now after that the appletviewer tool is used to view the output.

 appletviewer First.java

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

To display an image using Applet

import java.applet.*;
import java.awt.*;

public class appletImage extends Applet{


Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(), "demo.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
}
 The getCodebase() method is also commonly used to establish a path to files or folders that
are in the same location as the class being run.
 MediaTracker allows applets to check to see whether an image has loaded or not. Applets
can register images with a MediaTracker object, and then wait until one or all images have
loaded

To play sound using Applet

Play a sound using an applet image using getAudioClip(), play() & stop() methods of AudioClip() class.

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

public class PlaySoundApplet extends Applet implements ActionListener


{
Button play,stop;
AudioClip audioClip;
public void init()
{
play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "Sound.wav");
}
public void actionPerformed(ActionEvent ae)
{
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop ")
{
audioClip.play();
}
else if(source.getLabel() == " Stop ")
{
audioClip.stop();
}
}
}

Drawing different Geometric Shapes

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;

public class Shapes extends Applet


{
public void paint(Graphics g)
{
g.drawString("welcome to applet",100,400);
g.drawLine(50,20,200,10);
g.setColor(Color.yellow);
g.fillOval(100,50,200,100);
g.setColor(Color.red);
//g.drawRect(100,200,200,100);
g.fillRect(100,200,200,100);
}
}
/*
<applet code="Shapes.class" width="500" height="500">
</applet>
*/

Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
3. 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.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
5. 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.
6. 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).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle):
is used draw a circular or elliptical arc.
9. 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.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.

Using Font Class

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;

public class FontTest extends Applet


{
public void paint(Graphics g)

{
Font pfont = new Font("Serif", Font.PLAIN, 24);
g.setFont(pfont);
g.drawString("Welcome to Applet Font", 50, 70);
Font ifont = new Font("Serif", Font.ITALIC, 24);
g.setFont(ifont);
g.drawString("Welcome to Applet Font", 50, 120);
Font bfont = new Font("Serif", Font.BOLD, 24);
g.setFont(bfont);
g.drawString("Welcome to Applet Font", 50, 170);
Font bifont = new Font("Serif", Font.BOLD+Font.ITALIC, 24);
g.setFont(bifont);
g.drawString("Welcome to Applet Font", 50, 220);
}
}
/*
<applet code="FontTest.class" width="500" height="500">
</applet>
*/

Output:
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 :

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);
}
}

myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

Output:
Java AWT Tutorial

 Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based


application in java.
 Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system.
 AWT is heavyweight i.e. its components uses the resources of system.
 The java.awt package provides classes for AWT api such
 as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like
button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.

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.

Java AWT Example

To create simple awt example, we need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)

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);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
First f=new First();
}
}

Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for windows, is
event driven. Event describes the change in state of any object. For Example : Pressing a button,
Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified when an event
occurs.

How Events are handled


 A source generates an Event.
 This is send to one or more listeners registered with the source.
 Once event is received by the listener, they process the event and then return.
 Events are supported by a number of Java packages, like java.util, java.awt and java.awt.event.

Important Event Classes and Interface

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item ActionListener


is selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also
when it enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or textfield TextListener


is changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened or
closed

ComponentEvent generated when component is hidden, moved, ComponentEventListener


resized or set visible

ContainerEvent generated when component is added or ContainerListener


removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses FocusListener


keyboard focus

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example
that sets the position of the component it may be button, textfield etc.

Steps to handle events:


1. Implement appropriate interface in the class.
2. Register the component with the listener.

For registering the component with the Listener, many classes provide the registration methods. For
example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Example of event handling within class:

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

class EventTest1 extends Frame implements ActionListener


{
TextField tf;
EventTest1()
{

tf=new TextField();
tf.setBounds(60,50,170,20);

Button b=new Button("click me");


b.setBounds(100,120,80,30);

b.addActionListener(this);

add(b);add(tf);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[])
{
new EventTest1();
}
}

Example : Sum of two Numbers

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

public class SumFrame extends Frame implements ActionListener


{
Label l1;
TextField tf1,tf2,tf3;
Button b;
SumFrame()
{
l1=new Label("Sum of Two Numbers");
l1.setBounds(100,50,100,20);

tf1=new TextField();
tf1.setBounds(100,100,100,20);

tf2=new TextField();
tf2.setBounds(100,130,100,20);

tf3=new TextField();
tf3.setBounds(100,160,100,20);

b=new Button("Sum");
b.setBounds(100,190,100,30);

b.addActionListener(this);
add(l1);
add(tf1);add(tf2);add(tf3);
add(b);

setSize(300,300);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
int a=Integer.parseInt(tf1.getText());
int b=Integer.parseInt(tf2.getText());
int c;
c=a+b;
tf3.setText(""+c);
}

public static void main(String args[])


{
SumFrame f=new SumFrame();
}
}

Output:

Example - Checkbox

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

public class CheckBoxFrameTest extends Frame implements ItemListener


{
Label l1;
Checkbox c1,c2,c3;
String s;
CheckBoxFrameTest()
{
s="Checkbox Test";
c1=new Checkbox("C Program");
c2=new Checkbox("C++ Program");
c3=new Checkbox("Java Program");
add(c1);add(c2);add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}

public void itemStateChanged(ItemEvent e)


{
repaint();
}

public void paint(Graphics g)


{
g.drawString(s,100,130);
g.drawString("C :"+c1.getState(),100,150);
g.drawString("C++ :"+c2.getState(),100,170);
g.drawString("Java :"+c3.getState(),100,190);
}

public static void main(String args[])


{
CheckBoxFrameTest f=new CheckBoxFrameTest();
}
}

BorderLayout (LayoutManagers):
LayoutManagers:
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:
1. java.awt.BorderLayout 2.java.awt.FlowLayout
2. java.awt.GridLayout 4.java.awt.CardLayout 5.java.awt.GridBagLayout
6. javax.swing.BoxLayout 7.javax.swing.GroupLayout 8.javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center.
Each region (area) may contain one component only. It is the default layout of frame or window. The
BorderLayout provides five constants for each region:
1. public static final int NORTH 2. public static final int SOUTH
3. public static final int EAST 4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class:

import java.awt.*;
import javax.swing.*;

public class Border {


JFrame f;
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

You might also like