You are on page 1of 29

Applets

Kuldeep Yogi
Banasthali Unuversity
Part of the AWT Class Hierarchy
Object

Component

Button Checkbox Choice List Label Canvas


TextComponent Container ScrollBar

TextArea TextField Panel Window ScrollPane

Applet
Dialog Frame
Java Applet

public class className extends java.applet.Applet


{

public void init() {}

public void paint(Graphics g) {}


}
Java Applet
Applets will have the following methods:
public void init ( ) { //in here you will
//set fonts –may be done in paint instead
//set initial background and foreground collors
//initialize attributes (if other than their defaults)
//add components and/or event listeners
}
public void actionListenerType (EventType e) {
//needed
// for event driven applets – may occur in a component subclass
//do some action that will change the applet display
repaint();
}
public void paint(Graphics g) {
//only implicitly called by repaint
}
Additional Applet Methods

public void start ( ) {


//called after init and before the first invocation of paint
//if applet is stopped and restarted, start is called
//Netscape calls start and stop when the browser window is resized
//IE and appletviewer don’t
}
public void stop() {
//called when user leaves page containing the applet
}
public void destroy() {
//called when applet is about to be permanently destroyed –
//when browser shuts down or when ir removes the applet from memory
//Called by IE when user leaves the page containing the applet
}
HelloWorldApplet1.java
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.applet.Applet;

public class HelloWorldApplet1 extends Applet {

Font f = new Font("TimesRoman", Font.BOLD, 36);


String name,greeting;

public void init() {


name = ”Roger L. Norton";
greeting = new String("Hello " + name + "!");
}

public void paint(Graphics g) {


g.setFont(f);
g.setColor(Color.red);
g.drawString(greeting, 5, 40);
}
}
Java HTML APPLET Tag

<APPLET CODE= “…” WIDTH = xxx HEIGHT= yyy …>

….
</APPLET>

Options:
CODEBASE Designates the base URL

ALIGN Designates the applet alignment choice (Left, Right, Top, Bottom, Middle)

HSPACE Designates the empty space at the right and left of the applet

VSPACE Designates the empty space above and below the applet

NAME Designates the name of the applet

ARCHIVE Designates an archive of classes to preload


<HTML>
<HEAD>
<TITLE>
Hello World Example!
</TITLE>
</HEAD>
<BODY>
<H2>
Event Driven Software Java Lecture 2
</H2>
<P>
<APPLET code="HelloWorldApplet1.class" width="500" height="50">
Hello World!
</APPLET>
</P>
<P>
<A href="HelloWorldApplet1.java">The Source</A>
</P>
</BODY>
</HTML>
Java HTML APPLET Tag

<APPLET CODE= “…” WIDTH = xxx HEIGHT= yyy …>


Some text to be displayed if browser does not support java

<PARAM NAME = “…” VALUE = “…”>


<PARAM NAME = “…” VALUE = “…”>
</APPLET>
HellowWorldApplet2.html
<HTML>
<HEAD>
<TITLE>
Hello World Example!
</TITLE>
</HEAD>
<BODY>
<H2>
Event Driven Software Java Lecture 1
</H2>
<P>
<APPLET code="HelloWorldApplet.class" width="500" height="50">
<PARAM name="name" value=“Kuldeep Yogi">
Hello World!
</APPLET>
</P>
<P>
<A href="HelloWorldApplet.java">The Source</A>
</P>
</BODY>
</HTML>
HelloWorldApplet3.html
<HTML>
<HEAD>
<TITLE>
Hello World Example!
</TITLE>
</HEAD>
<BODY>
<H2>
Event Driven Software Java Lecture 1
</H2>
<P>
<APPLET code="HelloWorldApplet.class" width="500" height="50">
Hello World!
</APPLET>
</P>
<P>
<A href="HelloWorldApplet.java">The Source</A>
</P>
</BODY>
</HTML>
An Interesting Example
import java.awt.Graphics;
import java.awt.Color;

public class ColorBoxes extends java.applet.Applet {

void delay(int time){


for(int i =1;i<=time;i++);
}

public void paint(Graphics g) {


int rval, gval, bval;
String tempDelay = getParameter("delay");
int finalDelay = Integer.parseInt(tempDelay);

for (int k = 1;k<=100;k++){


for (int j = 30; j < (size().height -25); j += 30)
for (int i = 5; i < (size().width -25); i += 30) {
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);

g.setColor(new Color(rval,gval,bval));
g.fillRect(i, j, 25, 25);
g.setColor(Color.black);
g.drawRect(i, j, 25, 25);
};
delay(finalDelay);
};
};
}
ColorBoxes.html
<HTML>
<HEAD>
<TITLE>
Colored Boxes
</TITLE>
</HEAD>
<BODY>
<H2>
Event Driven Software Example #3
</H2>
<H2>
Colored Boxes
</H2>
<P>
<APPLET code="ColorBoxes.class" width="600" height="300">
<PARAM name="delay" value="10000000">
</APPLET>
</P>
<P>
<A href="ColorBoxes.java">The Source</A>
</P>
</BODY>
</HTML>
Control Fundamentals
The AWT supports the following types of controls
1. Label
Constructor:-
Label()
Label(String s)
Label(String ,Int how)
Here how may be Label.LEFT,Label.RIGHT,Label.Center
Methods:-
setText(String s)
getText()
setAlignment()
getAlignment()
2. Button
Constructor:-
Button()
Button(String s)
Methods:-
getLabel()
setLabel()
3. Checkbox
Constructor:-
Checkbox();
Checkbox(String s)
Checkbox(String s, boolean on)
Checkbox(String s, CheckboxGroup cgb ,boolean on)
Methods:-
getState()
setState()
getLabel()
setLabel()
4. CheckboxGroup
Constructor:-
CheckboxGroup()
Methods:-
setSeletedCheckbox(Checkbox c)
Checkbox getSelectedCheckbox()
5. Choice
Constructor:-
Choice()
Methods:-
add(String s)
getSelectedItem()
getSelectedIndex()
getItemCount()
void select(int index)
void select(String s)
6. List
Constructor:-
List()
List(int n_row)
List(int r, boolean multiSelect)
Methods:-
add(String s),
add(String s, int index)
getSelectedItem()
int[] getSelectedIndexs()
String[] getSelectedItems()
7. TextField
Constructor:-
TextField()
TextField(int numChars)
TextField(String s)
TextField(String s,int numchars)
Methods:-
getText()
setText(String s)
getSelectedText()
isEditable()
setEditable(boolean b)
setEchoChar(Char c)
echoCharIsSet()
getEchoChar()
Events in Java
In Java most objects within the AWT class hierarchy have the ability to
observe events occurring with respect to itself (e.g. a button can observe that
it has been pressed, or a textbox can detect that it has been written to). The
object can then send this information to any other object that has indicated
it is interested in knowing about such happenings. These notified objects
can then react to these events.

actionPerformed(Act
ButtonPanel
ionEvent)
Button
addActionListen
er(this)
getObjecct() buttonPressed

ActionEvent
8. TextArea
Constructor:-
TextArea()
TextArea(int numLines, int numChars)
TextArea(String s)
TextArea(String s,int numLines, int numchars)
TextArea(String s,int numLines, int numchars,int Bars)

Bars= SCROLLBARS_BOTH, SCROLLBARS_NONE, SCROLLBARS_HORIZONTAL_ONLY,


SCROLLBARS_VERTICAL_ONLY
Note:- This is a subclass of TextComponent class so it supports all methods which supported by
TextField class.
Additional Methods:-
append(String s)
insert(String s, int index)
replaceRange(String s, int startIndex, int endIndex)

9. MenuBar
To create a menubar first create a frame in which you want to display the menus.
Frame f =new Frame(“Menu”);
MenuBar mbar=new MenuBar();
Menu file=new Menu(“file”);
MenuItem New=new MenuItem(“New”);
CheckBoxMenuItem CB=new CheckBoxMenuItem(“dfd”);
f.setMenuBar()
file.add(New);
file.add(CB);
f.setVisible()
Dialog Box
Constructor
Dialog(Frame f, boolean mode)
Dialog(Frame f, String title,boolean mode)

FileDialog
Constructor
FileDialog(Frame f, String s)
FileDialog(Frame f,String s, int how)
FileDialog(Frame f)
How=FileDialog.LOAD , FileDialog.SAVE

Methods
getFile()
getDirectory()
Events in Java An event source:
can register listener object
can send listeners “event objects”
A listener object:
implements a “listener interface”
can be registered as a listener to various event sources

(ActionEvent actionPerformed)

ButtonPanel Button
addActionListener(this)

getObjecct() buttonPressed

An event object:
ActionEvent
contains information about the event that occurred
can be queried to receive this information
Event Listeners for Mouse and Keyboard Events
MouseListener
public void mouseEntered(MouseEvent e)
public void mouseExited (MouseEvent e)
public void mousePressed (MouseEvent e)
public void mouseReleased (MouseEvent e)
public void mouseClicked (MouseEvent e) Pressed and released at same location

MouseMotionListener
public void mouseMoved (MouseEvent e)
public void mouseDragged (MouseEvent e)

KeyListener
public void keyPressed(KeyEvent e)
public void keyReleased(keyEvent e)
public void keyTyped(keyEvent e)
Keyboard and Mouse Events

AWTEvent contains four important methods:


consume //delete the event
isConsumed //returns boolean – true if consumed by another
//listener on same source
getID //and int represening the event type
getSource //the Object that the event came from

KeyEvent adds the following methods:


getKeyChar //returns character typed
setKeyChar //replace the character with a different one
getKeyCode //returns an integer value which can be passedto
//getKeyText
isActionKey //differentiates function and arrow keys from normal key

isAltDown, isShiftDown, isControlDown


Keyboard and Mouse Events
MouseEvent methods:
methods
getX, getY //determine location of the mouse event
getClickCount //differentiates between single and double clicks
getModifiers //to determine which button was pressed

ActionListioner Interface
Void actionPerformed(ActionEvent ae)

FocusListener Interface
FocusEvent methods
Void focusGained(FocusEvent fe)
Void focusLost(FocusEvent fe)

ItemListerner Interface
Void itemStateChanged(ItemEven ie)
TextListener Interface
TextEvent Methods
Void textChanged(TextEvent te)

WindowListerner Interface
WindowEvent Methods
Void windowActivated(WindowEvent we)
Void windowClosed(WindowEvent we)
Void windowClosing(WindowEvent we)
Void windowDeactivated(WindowEvent we)
Void windowOpened(WindowEvent we)
Adapter Classes
If we are implementing a particular listener interface, we have to implement all the
methods defined in that interface. which might not actually be used. In order to simplify
things, Java came up with the concept of Adapter classes. Adapter classes provide empty
definitions for all the methods of their corresponding Listener interface.

JDK defines following adapter classes

ComponentAdapter
ContainerAdapter
FocusAdapter
HierarchyBoundsAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.*;
Public class AdapterDemo extends Applet
{
int xcord,ycord;
public void init()
{
addMouseMotionListner(new MouseDemo(this));
}
public void paint(Graphics g)
{
g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,ycord);
}
}
Class MouseDemo extends MouseMotionAdapter
{
AdapterDemo d;
MouseDemo(AdapterDemo d)
{
this.d=d;
}
Public void mouseMoved(MouseEvent me)
{
d.xcord=me.getX(); d.ycord=me.getY(); d.repaint();
}
}
Anonymous Inner Class
It is a class that is not assigned a name and created on the fly. They are created,
instantiated, used and garbage collected when they are done. They are automatically assigned a
name as Outerclassname$1.
Example: The syntax new KeyAdapter() {…….} indicates to the compiler that the
Import java.awt.*;
Code between the braces defines an anonymous inner class. This class
Import java.awt.event.*;
Import java.applet.*;
Extends KeyAdapter .
Public class AnonyKeyListDemo extends Applet
{
public void init()
{
addKeyListener (new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
showStatus(“key pressed”);
}
public void keyReleased(KeyEvent me)
{
showStatus(“KeyReleased”);
}
})
}
}
Testing an Applet

Construct an HTML file that will locate your applet in a region of an html
page.

Run appletviewer with the name of the html file where you call your applet.

You might also like