You are on page 1of 81

Java & J2EE

Introduction to Java GUI


Applets
• Applet Basics
• Architecture
• Applet Lifecycle
• repaint ( ), Update
• HTML APPLET Tags
• passing parameters to Applets
Applets
Applet
An applet is a special kind of Java program that a
Java enabled browser can download from the
internet and run.

Advantages of applets
– Security
– Portability :cross-platform support and
interactivity
• Security
It has limited access to resources so that it
can produce a graphical user interface
and run complex computations without
introducing the risk of viruses or
breaching data integrity
Difference b/n Applets and other
Java applications
Both the applets and standalone applications are
JAVA programs. But applets differ from other
JAVA applications in the following terms:

• Applets are not full-featured application


programs. They are usually written to
accomplish a small task or a component of a
task
• Applets have many limitations &
restrictions in their design since they are
used in Internet.

• The applet version has no main method


for initiating the execution of the code.
Applets when loaded automatically call
certain methods of applet class to start
and execute the applet code.
• Applets cannot run independently. They
are run from inside a web page using
special feature known as HTML tag

• Applets cannot read from or write to the


files in the local computer.

• Applets cannot communicate with other


servers on the network
• Applets cannot run any program from the
local computer.

• Applets are restricted from using other


languages libraries such as C, C++.
• GUI components are added directly to the
Applet;
whereas, in the case of an application,
GUI components are added to the content
pane of its JFrame object.
NOTE:
All the restrictions and limitation for
applets are placed in the interest of
security of systems. These restrictions
ensure that an applet cannot do any
damage to the local system
Two Types of applets
1. Applets based directly on Applet class

2. Applets based on the Swing class


JApplet
Applets based directly on Applet class

• Use the Abstract Window Toolkit (AWT)


to provide the graphic user interface

• Have been available since JAVA was first


created
Applets based on the Swing class Japplet

• Uses Swing classes to provide the GUI


which offers a richer and often easier-to-
use user interface than does the AWT

• Swing based applets are most popular

• JApplet inherits Applet


JApplet hierarchy is as follows:

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
Applet Basics
• All applets are subclasses of Applet, either
directly or indirectly
• Applets are not stand-alone programs
• They run either within a web browser or an
applet viewer
• Execution of an applet doesn't begin at main()
• O/p to applet’s window is not performed by
System.out.println
• To use an applet, it is specified in an HTML
file, using the APPLET tag
• The applet will be executed by a JAVA enabled
web browser when it encounters the APPLET
tag within the HTML file.
• To view and test an applet more conveniently,
simply include a comment at the head of the
Java source code file that contains the
APPLET tag
Example:
/*
<applet code = “MyApplet”
width=200
height=60>
</applet>
*/
The Applet class
• Applet class defines the methods to provide all
necessary support for applet execution such as
– Starting
– Stopping
– Load & display image
– Load & play audio clips
• Applet extends the AWT class Panel, Panel
extends Container, which extends Component.
• All the above classes provide support for java’s
window-based, graphical interface.
• Applet provides all of the necessary support for
window based activities
Applet architecture
Applet is a window based program.
• Event driven applets
• Interactive applets
Event driven applets
• Based on event driven architecture
• Resembles a set of interrupt service routines
• An applet waits until an event occurs. The run-
time system notifies the applet about an event
by calling an event handler that has been
provided by the applet. Once this happens, the
applet must take appropriate action and then
quickly return.
• If the applet needs to perform a repetitive task
on its own, then an additional thread of
execution must be started.
Interactive applets
• User initiates interaction with the an applet
• User interactions are sent to the applets as
events to which the applet must respond
Example:
when user clicks the mouse inside the applet’s
window, a mouse-clicked event is generated
If the user presses a key while the applet’s
window has input focus, a keypress event is
generated
Applet Lifecycle
• Applets can override a set of methods that
provides the basic mechanism by which the
browser or applet viewer interfaces to the
applet and controls its execution

• The methods are:


– init()
– stop()
– start()
– destroy()
– paint()
• These methods apply to all applets and are
defined by Applet class.
• Default implementations for all of these
methods are provided.
• Applets may or may not override these
methods
• These five methods form the Applet skeleton

AppletSkeleton.java
Applet life cycle
• Every Java applet inherits a set of default
behaviors from the Applet class
• When an applet begins,
– init()
– start()
– paint() are called in sequence
• When an applet is terminated
– stop()
– destroy() are called in sequence
init( )
• Is the first method to be called
• Initializes the variables
• Called only once during the run time of
applet
start( )
• Is called after init()
• Is also called to restart an applet after it
has been stopped.
• Is called each time an applet’s HTML
document is displayed onscreen
paint( )
• Is called each time when an applet’s o/p must
be redrawn
• Is also called when the applet begins execution
• paint() has one parameter of type Graphics,
which will contain the graphics context, that
describes the graphics environment in which
the applet is running
stop( )
• Is called when a web browser leaves the
HTML document containing the applet.
• Is called, probably when an applet is
running
• Is also used to suspend threads that don’t
need to run when the applet is not visible
destroy( )
• Is called when the environment
determines that applet needs to be
removed completely from memory

• stop() method is always called before


destroy()
update( )
• Is a method defined by AWT
• Can be overridden
• Is called when applet has requested that a
portion of its window be redrawn
• Default version of update() simply calls
paint()
Simple applet display methods

• The output for an applet is displayed


using one of the member of graphics
class called “drawString( )”

• It is used/called either within update() or


paint()
General form:
void drawString(String message, int x, int y)

where message is the string to be o/p beginning


at (x, y)

NOTE:
drawString() doesn’t recognize newline
characters, must be specified by x,y location
Sample applet program demonstrating
drawString( )

welcomeApplet.java
• To set the color of an applet’s window
– setBackground()
– setForeground()
methods are defined by Component class

• General form:
void setBackground(Color newColor)
void setForeground(Color newColor)
• The class Color defines the constants.

Example:
setBackground(Color.green);
setForeground(Color.red);

• Usually color are set in init()


• Current color settings can be obtained by
calling
getBackground( )
getForeground( )
methods are defined in Component class
Colors
• The java.awt package defines a class named
Color
• There are 13 predefined colors:
Color.BLACK Color.PINK
Color.GREEN Color.DARK_GRAY
Color.RED Color.CYAN
Color.GRAY Color.ORANGE
Color.BLUE Color.LIGHT_GRAY
Color.YELLOW Color.WHITE
Color.MAGENTA
NOTE:
For compatibility with older programs (before
the naming conventions were established),
Java also allows color names in lowercase:
Color.black, Color.darkGray, etc.

SetBgFgColor.java
Using the status window

An applet can also output a message to the


status window of the browser or applet
viewer on which it is running, using the
function showStatus() with the string to
be displayed
• Status window helps in
– Giving user feedback about what occurring
in the applet
– Suggests options
– Report some types of errors
– Is a debugging aid

StatusWinDemo.java
repaint ( )
update( )
• Applets writes to its window with
update() or paint() method

• To repaint/update the information


displayed in the window, applet calls
repaint()
repaint()
• Is defined by AWT
• Causes AWT run-time system to execute a call
to applet’s update() method, which, in its
default implementation calls paint()

Example:
If a part of the applet needs to output a string, it
can store this string in a string variable and
then call repaint()
Four forms of repaint:
• void repaint( )
Causes entire window to be repainted

• void repaint(int left, int top, int width,


int height)
Causes a region to be repainted
• void repaint(long maxDelay)
• void repaint(long maxDelay, int x, int y,
int width, int height)

These methods are used when consistent


update time is necessary. maxDelay
specifies the maximum number of
milliseconds that can elapse before
update() is called
Program to demonstrate repaint():
This applet creates thread that scrolls the
message contained in “msg” from left to
right across applet’s window

SimpleBanner.java
HTML APPLET Tags
• APPLET tag is used to start an applet
from both an HTML document and from
an applet viewer

• Applet viewer executes each APPLET tag


in a separate window

• Web-browser allow many applets on a


single page
The syntax for a fuller form of the APPLET tag is:
< APPLET
[CODEBASE = codebase URL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[< PARAM NAME = appletParameter1 VALUE = value>]
[< PARAM NAME = appletParameter1 VALUE = value>]

[ alternateHTML]
</APPLET>
CODEBASE
• Optional attribute
• Specifies the base URL of the applet code,
which is the directory that will be searched for
the applet’s executable class file
• If the codebase attribute is absent, then the
HTML document’s URL directory is used
• Doesn’t have to be on the host from which
HTML document was read
CODE
• Required attribute
• Gives the name of the file containing applet’s
compiled .class file
• .class file is relative to the code base URL of
the applet, which is the directory that the
HTML file was in or the directory indicated by
CODEBASE if set
ALT
• Optional attribute

• Used to specify a short text message that


should be displayed if the browser recognizes
the APPLET tag but can’t currently run JAVA
applets
NAME
• Optional attribute
• Used to specify a name for the applet instance
• Applets must be named in-order for other
applets on the same page to find them by name
and communicate with them
• getApplet(), which is defined by
AppletContext interface, obtains applet by
name
WIDTH and HEIGHT
• Are required attribute
• Gives the size (in pixels) of the applet display
area
ALIGN
• An optional attribute
• Specifies the alignment of the applet
• Has possible values: LEFT, RIGHT, TOP,
BOTTOM, MIDDLE, BASELINE, TEXTOP,
ABSMIDDLE, ABSBOTTOM
• VSPACE and HSPACE
• Are optional attributes
• VSPACE specifies the space in pixels, above &
below applet
• HSPACE specifies the space in pixels, on each
side of the applet.
PARAM NAME and VALUE
• Specify applet –specific arguments in an
HTML page

• Applets access their attributes with the


getParameter() method
Passing parameters to
Applets
• APPLET tag in HTML allows to pass
parameters to the applet

• getParameter() method retrieves a parameter.


– Returns the value in the form of a string

ParamDemo.java
getDocumentBase( )
getCodeBase( )
• To know the directory that holds the HTML
file that started the applet. i.e. document base

getDocumentBase( ) method is used


- gets the URL of the document in which the
applet is embedded

• Directory is returned as URL object


• To know the directory from which applet’s
class was loaded. i.e. code base

getCodeBase( ) method is used


- gets the base URL of the applet.

• Directory is returned as URL object

DocumentCodeBase.java
AppletContext
showDocument( )
AppletContext interface:
• Gives information about the applet’s execution
environment (getAppletContext( ) )

• Other methods supported are:


getAudioClip( )
getImage( )
showDocument( )
showStatus( )
showDocument( )
• Used by applet to transfer control to
another URL for navigating web.
• is defined in AppletContext interface.
• Has no return value and doesn’t throw
any exception if it fails.
• showDocument(URL url) – displays the
document at the specified URL.
• showDocument(URLurl, String where)
displays the specified document at the
specified location within the browser window.
• where can be:
_self – show in current frame
_parent – show in parent frame
_top – show in topmost frame
_blank – show in new browser window

showDocument.java
AudioClip
AppletStub
AudioClip interface
• Defines methods for playing audio clips

play( ) – play a clip from beginning


stop( ) – stop playing the clip
loop( ) – play the clip continuously
getAudioClip( ) – to load an audio clip
AppletStub interface

• Provides the means by which an applet


and the browser or appletviewer
communicates
Limitations of applets
Limitations of applets
• requires Java Plug-In and Java Runtime
Environment in order to run an embedded Java
applet in the browser
• Poor applet startup performance
• Client Security Settings Interference
• Proxy Server Interference
• Plug-In and JRE Requirements
The most significant disadvantage facing Java
applets is that clients must already possess a
copy of the Java Runtime Environment (JRE)
for their operating system as well as a Java
plug-in for their browser in order to run an
embedded Java applet. If the JRE is not
already installed, the applet will not function
and will appear just as an empty box
containing the Java logo.
• Poor applet startup performance
Because the entire JRE must be loaded from the hard disk the
first time a Java applet is called upon, the startup time for the
first Java applet run on a machine since its last reboot can be
much longer than if the developers had went with an
alternative to Java applets for their Web application.
In addition, although the applet runs inside the user's Web
browser, it still must be fully downloaded onto the client's
machine before it can be used. Large applets may be especially
slow to load for clients that have slow connections to the
Internet. This problem is made dramatically worse if the client
has an older version of the JRE than the one which is required
by the applet. In this case, the applet must request that the new
JRE be downloaded before it can run.
• Client Security Settings Interference
Because the applet is really a program that is
run on the client's computer, rather than the
Web server, strict security settings on the client
side may interfere with the operation of applet.
Consequences can range from the failure of
specific features to the complete inability of
the applet to start
• Proxy Server Interference
Many users and organizations use an advanced
network configuration known as a "proxy
server" to access the Internet. These
configurations can make it difficult for the
Java Runtime Environment to perform
automatic updates that an applet may request
when it needs more advanced and newer
features than are available in the current JRE
Exercises
Write an applet program to perform the
bubble sort on a list of numbers.

appletBubble.java
Write an applet program to perform the
linear search on a list of numbers.
Pass the key as parameter to the
applet.

appletLinear.java