Sas Java Unit 6
Sas Java Unit 6
Sas Java Unit 6
APPLETS
What is an Applet?
Applet is a small java program primarily used for Internet computing or Applet is a java
program that can be embedded into a web page. They can run using Applet Viewer or any web
browser that supports java.
Advantages
It works at client side so less response time.
Applets are safe and secure.
It can be executed by any java-enabled browser running under different platforms,
including Linux, Windows, Mac OS etc.
Automatically integrated with HTML; hence, resolved virtually all installation issues.
Can provide dynamic, graphics capabilities and visualizations.
Alternative to HTML GUI design.
Can be launched as a standalone web application independent of the host web server
Disadvantages
Plug-in is required at client browser to execute applet.
Stability depends on stability of the client’s web server
Performance directly depend on client’s machine
Applets cannot read from or write to the files on the local computer.
Applet cannot communicate with the other servers on the network.
Applet cannot run any program from the local computer.
Applet are restricted from using libraries from other languages such as C or C++. (Java
language supports this feature through native methods)
Applet Types
Applets are of two types.
1. One which use the AWT (abstract window toolkit) to draw and display
graphics.(Use Applet class)
2. Another type which uses Swing for drawing and display of graphics. (Use JApplet
class).
3
JAVA PROGRAMMING
Life Cycle Methods
1. public void init()
This method is called at the time of starting the execution. This is called only once in the life
cycle. This method initializes the Applet and it helps to initialize variables and instantiate the
objects and load the GUI of the applet. This is invoked when the page containing the applet is
loaded and places the applet in new born state. Its gereral form is:
statements;
2. start() method
The start() method executes immediately after the init() method. It starts the execution
of Applet. In this state, the applet becomes active. The start() method contains the actual code
of the applet that should run. It also executes whenever the applet is restored, maximized or
moving from one tab to another tab in the browser.
{
3. stop() method statements;
The stop() method stops the execution of the applet. It is invoked when the Applet or the
browser is minimized. The Applet frequently comes to this state in its life cycle and can go back
to its active state.
public void stop()
statements;
4. paint() method
This method helps to create Applet’s GUI such as a colored background, drawing and writing.
The paint() method executes after the execution of start() method and whenever the applet or
browser is resized.
public void paint(Graphics g)
statements;
This method takes a java.awt.Graphics object as parameter.
5. destroy() method
This destroys the Applet and is also invoked only once when the active browser page containing
the applet is closed.
public void destroy( )
statements;
4
JAVA PROGRAMMING
Order of Execution
The method execution sequence when an applet is executed is:
init()
start()
paint()
The method execution sequence when an applet is closed is:
stop()
destroy()
Structure/Skeleton of Applet
import java.awt.*;
import
java.applet.*;
/*
<applet code="MyApplet" width=pixels height=pixels>
</applet>
*/
public class MyApplet extends Applet
{
public void init() {
// initialization
}
public void start() {
// start or resume execution
}
public void stop() {
// suspends execution
}
public void destroy() {
// perform shutdown activities
}
public void paint(Graphics g) {
// redisplay contents of window
}
}
How to run an Applet?
There are two ways to run an applet
1. By appletViewer tool (for testing purpose).
2. By html file. (Save the code with .html extesion)
5
JAVA PROGRAMMING
Filename.html
<html> <applet code = “filename.class" width = "xxx" height = "xxx">
</applet>
</html>
6
JAVA PROGRAMMING
Java API support for Applets
Java includes many libraries (a.k.a packages) and classes, commonly known as Java
API. java.applet is a small package used to develop applets. It contains 3 interfaces and 1 class.
They are:
Interfaces
AppletContext: Used by the programmer to communicate with the execution
environment of an applet. This is required to communicate between two applets.
AppletStub: Used to develop custom applet viewers. Programmer can utilize this
interface to communicate between applet and the browser environment.
AudioClip: Used to play audio clips. It comes with methods
like play(), loop() and stop().
Classes
1. Apple: This class should be extended by our applet program. Applet is a class inherited
from Panel of java.awt package.
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provides methods that load and display images and methods that
load and play audio clips.
Create an html file with <Applet > tag (MyApplet.html) using notepad
Create a java code for applet (HelloApplet.java)
Compile code and get class file (HelloApplet.class)
Run the html file(By web browser or by appletviewer)
7
JAVA PROGRAMMING
Step2: Create a java code for applet
MyApplet.java
import java.applet.*;
import
java.awt.Graphics;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}
}
Methods
Method Description
public abstract void drawString(String str, int used to draw the specified string.
x, int y)
public void drawRect(int x, int y, int width, Draw a rectangle with the specified width
int height) and height.
public abstract void fillRect(int x, int y, int Used to fill rectangle with the default color
width, int height) and specified width and height.
public abstract void drawOval(int x, int y, int Used to draw oval with the specified width
width, int height) and height.
public abstract void fillOval(int x, int y, int Used to fill oval with the default color and
width, int height) specified width and height.
public abstract void drawLine(int x1, int y1, Used to draw line between the points(x1, y1)
int x2, int y2) and (x2, y2).
8
JAVA PROGRAMMING
public abstract boolean drawImage(Image Used to draw the specified image.
img, int x, int y, ImageObserver observer)
public abstract void drawArc(int x, int y, int Used to draw a circular or elliptical arc.
width, int height, int startAngle, int
arcAngle)
public abstract void fillArc(int x, int y, int Used to fill a circular or elliptical arc.
width, int height, int startAngle, int
arcAngle)
public abstract void setColor(Color c) Used to set the graphics current color to the
specified color.
public abstract void setFont(Font font) Used to set the graphics current font to the
specified fonts
Example:
Java code:
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);
}
}
Html code:
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
The applet tag
Applets are embedded in HTML documents with the <APPLET> tag. It contains
attributes that identify the applet to be displayed and, optionally, give the web browser hints
about how it should be displayed.
Syntax:
<APPLET
[CODEBASE = CODEBASE_URL]
9
JAVA PROGRAMMING
CODE=class name [ALT=alternate_text]
[NAME = applet_instance_name] WIDTH pixels HEIGHT= pixels [ALIGN = alignment]
[VSPACE =pixels]
[ HSPACE =pixels]>
[ <PARAM NAME =name1 VALUE=value1>]
[ <PARAM NAME =name2 VALUE=value2>]
…………………….
[Text to be displayed in the absence of java]
</APPLET>
Attributes
CODEBASE: This attribute is used to specify the base URL of the applet -- the directory
or folder that contains the applet's code.
CODE: This required attribute gives the name of the file that contains the applet's
compiled Applet subclass.
ALT: Any text that should be displayed is specified by this optional attribute if the
browser understands the APPLET tag but can't run Java applets.
NAME: This optional attribute specifies a name for the applet instance. With the help of
this attribute it is possible for applets on the same page to find (and communicate with)
each other.
WIDTH, HEIGHT: The initial width and height of the applet is given by these attributes.
ALIGN: This attribute specifies the alignment of the applet with the following possible
values: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom
VSPACE, HSPACE: These optional attributes are used to specify the number of pixels
above and below the applet (VSPACE) and on each side of the applet (HSPACE).
<PARAM>: The only way to specify applet-specific parameters is to use the
<PARAM>tags. Applets read user-specified values for parameters with
the getParameter() method.
Inside the applet, you read the values passed through the <PARAM> tag with the
getParameter() method of the Applet class.
The getParameter() method of the Applet class can be used to retrieve the parameters passed
from the HTML page. String getParameter(String param-name);
Example Param.html
<html>
<body>
<applet code="MyApplet" height="100" width="200">
<param name="wish" value="Hello" />
10
JAVA PROGRAMMING
<param name="clg" value=”RIT" />
</applet>
</body>
</html>
Myapplet.java
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String w, c;
public void init()
{
w = getParameter("wish");
c = getParameter("clg");
}
public void paint(Graphics g)
{
g.drawString(w, 20, 20);
g.drawString(c, 50, 20);
}
}
Output
C:/> javac MyApplet.java
C:/>appletviewer Param.html
Output:
C:/> javac UserInput.java
C:/>appletviewer UserInput.java
12
JAVA PROGRAMMING
Event Handling
Event handling is at the core of successful applet programming. Events are
supported by the java.awt.event package. These events are passed to your applet in a
variety of ways, With the specific method depending upon the actual event.
There are several types of events. The most commonly handled events are those
generated by the mouse, the keyboard, and various controls, such as a push button.
The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events. A user
interface element is able to “delegate” the processing of an event to a separate piece of
code.
In the 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. There are mainly three parts in delegation
event model.
1. Events.
2. Event sources.
3. Event Listeners.
Events
An event is an object that describes a state change in a source. Some of the activities
that cause events to be generated are pressing a button, entering a character via the
keyboard, selecting an item in a list and clicking the mouse.
Event Sources
A source is an object that generates an event. A source must register listeners in
order for the listeners to receive notifications about a specific type of event. Each type of
event has its own registration method. Here is the general form:
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().
13
JAVA PROGRAMMING
Event Listeners
A listener is an object that is notified when an event occurs.
It has two major requirements.
1. First, it must have been registered with one or more sources to receive
notifications about specific types of events.
2. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved. Any object may receive and
process one or both of these events if it provides an implementation of this interface.
Event classes
The classes that represent events are at the core of Java’s event handling mechanism.
They provide a consistent, easy-to-use means of encapsulating events. At the root of the
Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all
events.
The class AWTEvent defined within the java.awt package, is a subclass of
EventObject. It is the superclass for all AWT-based events used by the delegation event
model.
The package java.awt.event defines several types of events that are generated by various
user interface elements.
14
JAVA PROGRAMMING
more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes
15
JAVA PROGRAMMING
keyTyped ( KeyEvent )
mouseClicked (
MouseEvent ) Button ,
MouseListener mouseEntered ( addMouseListener( ) Canvas, Panel
MouseEvent )
mouseExited (
MouseEvent )
mousePressed (
MouseEvent )
mouseReleased (
MouseEvent )
MouseMotionListenemouseDragged (MouseEvent ) addMouseMotionListen
Button ,
R mouseMoved ( MouseEvent ) er( ) Canvas,
Panel
TextListener textValueChanged ( TextEvent ) addTextListener( ) TextComponent
16
JAVA PROGRAMMING
String str="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent me)
{
str ="You pressed mouse";
repaint();
}
public void mouseReleased(MouseEvent me) {
str ="You released mouse";
repaint();
}
public void mouseClicked(MouseEvent me) {
str ="You clicked mouse";
repaint();
}
public void mouseEntered(MouseEvent me) {
str ="You entered applet window";
repaint();
}
public void mouseExited(MouseEvent me) {
str ="You exited applet window";
repaint();
}
public void mouseDragged(MouseEvent me) {
str ="You are dragging";
repaint();
}
public void mouseMoved(MouseEvent me) {
str ="You are moving mouse";
repaint();
}
public void paint(Graphics g)
{
g.drawString(str,75,75);
}
}
Output
17
JAVA PROGRAMMING
KeyEvent class
An event which indicates that a keystroke occurred in a component. It defines
several constants. They are:
1. public static final int KEY_PRESSED: The "key pressed" event. This event is
generated when a key is pushed down.
2. public static final int KEY_RELEASED: The "key released" event. This event is
generated when a key is let up.
3. public static final int KEY_TYPED: The "key typed" event. This event is generated
when a character is entered.
There are many other integer constants that are defined by KeyEvent.
For example:
VK_0 to VK_9, VK_A to VK_Z define the ASCII equivalents of the
numbers and letters.
The VK constants specify virtual key codes and are independent of any modifiers, such
as control, alt or shift,
Methods
1. public int getKeyCode(): Returns the integer keyCode associated with the key in this
event. Returns the integer code for an actual key on the keyboard.
2. public char getKeyChar(): Returns the character associated with the key in this event.
18
JAVA PROGRAMMING
For example, the KEY_TYPED event for shift + "a" returns the value for "A".
repaint();
}
public void keyReleased(KeyEvent ke) {
str ="You released key"; repaint();
}
public void keyTyped(KeyEvent ke) {
Output
javac KeyboardEvents.java
appletviewer
KeyboardEvents.java
19
JAVA PROGRAMMING
Inner classes
Java inner class or nested class is a class which is declared inside the class or
interface. They enable you to logically group classes and interfaces in one place, thus
increase the use of encapsulation. The scope of a nested class is bounded by the scope of
its enclosing class. A nested class can access all the members of outer class including
private data members and methods. However, reverse is not true.
A nested class is also a member of its enclosing class. A nested class can be
declared private, public, protected, or package private (default).
Advantages:
1. Nested classes represent a special type of relationship that is it can access all the
members of outer class including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
20
JAVA PROGRAMMING
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
Description
Class Description
A class created within class and outside
Member Inner Class method.
A class created for implementing interface or
Anonymous Inner Class extending class. Its name is decided by the
java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Output :
Age is 21
Local Inner class
A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.
22
JAVA PROGRAMMING
Java AWT
The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
23
JAVA PROGRAMMING
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.
24
JAVA PROGRAMMING
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager defines the layout manager for the component.
m)
public void setVisible(boolean status) changes the visibility of the component, by default
false.
Example1:
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();
}
}
Output:
Example2:
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
TextField t1,t2;
25
JAVA PROGRAMMING
t1=new TextField("name");
t1.setBounds(50,100,80,30);
t2=new TextField("class");
t2.setBounds(50,150,80,30);
f.add(t1);
f.add(t2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
Output:
C:/java/awt/javac First2.java
C:/java/awt/java First2
26