Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chap-2 Swing

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 19

Compiled by: Ramesh Bhatta Page 1

Introduction
A graphical user interface (GUI) presents a pictorial interface to a program. A GUI gives
a program a distinctive “look” add “feel”. GUI provides programs a set of user interface
components. This reduces the time that users require to learn a program and increases
their ability to use the program in a productive manner.
GUIs are built from GUI components (sometimes called controls or widgets – short
for window gadgets). A GUI component is an object with which the user interacts via the
mouse, the keyboard or another form of input, such as voice recognition.

Swing
The classes that create the GUI components are part of the Swing GUI components from
package javax.swing. Most Swing components are written, manipulated and displayed
completely in Java (so-called pure Java components).
The original GUI components from the Abstract Windowing Toolkit package java.awt
(also called the AWT) are tied directly to the local platform’s graphical user interface ca-
pabilities. When a Java program with an AWT GUI executes on different Java platforms,
the program’s GUI components display differently on each platform.
The Swing components allow the programmer to specify a uniform look and feel
across all platforms. In addition, Swing enables programs to provide a custom look and
feel for each platform or even to change the look and feel while the program is running.
Swing components are often referred to as lightweight components since they are
completely written in Java. AWT components that are tied to the local platform are corre-
spondingly called heavyweight components – they rely on the local platform’s windowing
system to determine their functionality and their look and feel. Several Swing compo-
nents are still heavyweight components. In particular, subclasses of java.awt.Frame
(such as JFrame) that display windows on the screen and subclasses of java.applet.Ap-
plet (such as JApplet) still require direct interaction with the local windowing system. As
such, heavyweight Swing GUI components are less flexible than many of the lightweight
components.
Example:
import javax.swing.*;
public class SwingExample extends JFrame{
public SwingExample() {
super("Simple swing example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
getContentPane().add(label);
pack();
setVisible(true);
}
}

public class MainProgram {


public static void main(String[]args) {

Advanced Java1 programming


Compiled by: Ramesh Bhatta Page 2

SwingExample ob = new SwingExample();


}
}
This is one of the simplest swing applications you can write. It doesn’t do much, but the
code demonstrates the basic code in every Swing program.

The first line imports the main Swing package:


import javax.swing.*;
This is the only package that SwingExample needs. However, most Swing programs also
need to import two AWT packages:
import java.awt.*;
import java.awt.event.*;
These packages are required because swing components use the AWT infrastructure, in-
cluding the AWT event model and layout manager. The event model governs how a com-
ponent reacts to events such as button clicks and mouse motion. The layout manager is
used to arrange components in many ways.
Every program with a Swing GUI must have at least one top-level Swing container. A
top-level Swing container provides the support for swing components. There are three
commonly used top-level swing containers: JFrame, JDialog, and (for applets) JApplet.
Each JFrame object implements a single main window, and each JDialog implements a
secondary window (a window dependent on another window). Each JApplet object im-
plements an applet’s display area within a browser window.
The SwingExample example has only one top-level container, a JFrame. A frame is a
window that, by default, has decorations such as a border, a title, and buttons for iconify-
ing and closing the window. Applications with a GUI typically use at least one frame.
Here is the code that sets up and shows the frame.
super("Simple swing Example");
...
pack();
setVisible(true);
With the exception of top-level containers, such as JFrame, all Swing components de-
scend from the JComponent class. SwingExample uses a JComponent descendant called
JLabel, which displays the text Hello World. These two lines of code construct and
then add the JLabel component to the frame:
JLabel label = new JLabel("Hello World");
getContentPane().add(label);
Note that the label is added to the frame’s content pane instead of to the frame itself. Ev-
ery top-level container has a content pane that contains, directly or indirectly, all the visi-
ble components (except for menus and window decorations) in the top-level container.
To make the program exit when the Close button is clicked, we include the following
code.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Advanced Java2 programming


Compiled by: Ramesh Bhatta Page 3

Using Top-Level Containers


Swing provides three generally useful top-level container classes: JFrame, JDialog, and
JApplet. Each program that uses Swing components has at least one top-level container.
This top-level container is the root of a containment hierarchy – the hierarchy that con-
tains all of the Swing components that appear inside the top-level container. We add
components to top-level container’s content pane. For example, getContentPane().add(la-
bel);
In theory, all top-level containers can hold a menu bar. In practice, however, menu
bars usually appear only in frames and applets. To add a menu bar to a top-level con-
tainer, create a JMenuBar object, populate it with menus, and then call setJMenuBar
method.

The JFrame Class


JFrame extends the AWT class Frame. It has a title bar, menu bar, borders, and resizing
corners. It contains additional features that enable it to support Swing components. If you
are creating an application (rather than an applet), then you will typically use JFrame as
the top-level (that is, main) window. Its two constructors are:
JFrame() – crates a standard window that does not contain a title.
JFrame(String str) – crates a window with the title specified by title.
There are several methods you will use when working with JFrame. Some of them are
given below:
void setSize(int newWidth, int newHeight) – sets dimensions of the window specified by
newWidth and newHeight.
void setSize(Dimension newSize) – sets dimensions of the window specified by width and
height fields of the Dimension object passed in newSize.
Dimension getSize() – obtain the current size of the window.
void setVisible(Boolean visibleFlag) – sets the visible property of the window. The win-
dow is visible if the argument to this method is true. Otherwise, it is hidden.
void setTitle(String newTitle) – changes or sets title in the frame window. The newTitle is
the new title for the window.

Swing Components
With the exception of top-level containers, all Swing components whose name begins
with “J” descend from the JComponent class. For example, JButton, JTextField, JLabel
etc. all inherit from JComponent. To include a component in a Window, you must add it
to the window. To do this, you must first create an instance of the desired component and
then add it to a window by calling add(), which is defined by Container class. There are
several forms of add() method. The following form is most common:
Component add(Component compObj)
Here compObj is an instance of the component that you want to add. Once a control has
been added, it will automatically visible whenever its parent window is displayed.

Advanced Java3 programming


Compiled by: Ramesh Bhatta Page 4

Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove(). This method is also defined by Container. It has
the following general form:
void remove (Component obj)
Here, obj is a reference to the control you want to remove. You can remove all con-
trols by calling removeAll(). It has the following general form:
void remove ()
Some most commonly used swing components are discussed below:
Icons and Labels
Icons are encapsulated by the ImageIcon class, which paints an icon from an image. The
two types of constructors are shown here:
ImageIcon(String filename) – uses the image in the file named filename.
ImageIcon(URL url) – uses image in the resource identified by url.
A label displays a single line of read-only text, an image or both text and an image. La-
bels are defined with class JLabel. Some of its useful constructors are:
JLabel() – creates a blank label.
JLabel(String str) – creates a label that contains the string specified by str.
JLabel(String str, int align) – creates a label that contains the string specified by str using
the alignment specified by align. The align argument is JLabel.LEFT, JLabel.RIGHT,
JLabel.CENTER, JLabel.LEADING, or JLabel.TRAILING.
JLabel(Icon image) – creates a label that contains the icon specified by image.
JLabel(Icon image, int align
JLabel(String str, Icon image, int aling)
There are several methods you will use when working with JLabel. Some of them are
given below. These methods can read and write icon and text associated with the label.
Icon getIcon()
String getText()
Vod setIcon()
Void setText()
Text Fields
Text fields allow the user to enter one line text and edit using the arrow keys, cut and
paste keys, and mouse selection. Text fields are defined with the class JTextField. Sev-
eral of its constructors are shown here:
JTextField()
JTextField(int cols)
JTextField(String s)
JTextField(String s, int cols)
Here, s is the string to be initially presented, and cols is the number of columns in the text
field. Some of its methods are given below:

Advanced Java4 programming


Compiled by: Ramesh Bhatta Page 5

String getText() – returns string currently contained in the text field.


void setText(String str) – sets the text specified by str in the text field.
String getSelectedText() – returns the selected in the text field.
void select(int startIndex, int endIndex) – selects the characters beginning at startIndex
and ending at endIndex-1.
boolean isEditable() – returns true if the text may be changed and false if not.
void setEditable(boolean canEdit) – if canEdit is true, the text may be changed. If it is
false, the text cannot be altered.
Buttons
The most widely used component is the push button. A push button is a component that
contains a label and generates an event when it ispressed. The JButton class provides the
functionality of a push buttons. It allows an icon, a string, or both to be associated with
the push button. Some useful constructors are:
JButton() – creates an empty button.
JButton(Icon icon) – creates a button that contains icon as a label.
JButton(String text) – create a button that contains text as a label.
JButton(String text, Icon icon) – creates a button that contains text and icon as label.
There are several methods you will use when working with JButton. Some of them are
given below:
Icon getIcon() – retrives icon associated with the button.
String getText() – retrives text associated with the button.
boolean isSelected() – returns true if the button is selected.
void setIcon(Icon icon) – sets icon as its label.
void setText(String text) – sets text as its label.
Check Boxes
A check box is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not. There is a label associated with each check
box that describes what option the check box represents. You can change the state of a
check box by clicking on it. Check boxes can be used individually or as part of a group.
Check boxes are objects of the JCheckBox class. Some useful constructors are:
JCheckBox() – creates a checkbox whose label is blank. The state of the check box is
unchecked.
JCheckBox(String str) – creates a checkbox whose label is specified by str. The state of
the check box is unchecked.
JCheckBox(String str, boolean state) – creates a checkbox whose label is specified by str.
If state is true, the check box is initially checked; otherwise it is cleared.
JCheckBox(Icon i) – creates a checkbox with an icon i. The state of the check box is
unchecked.
JCheckBox(Icon i, boolean state) – creates a checkbox with an icon i. If state is true, the
check box is initially checked; otherwise it is cleared.
JCheckBox(String, str, Icon i, boolean state) – creates a checkbox with string str and an
icon i. If state is true, the check box is initially checked; otherwise it is cleared.

Advanced Java5 programming


Compiled by: Ramesh Bhatta Page 6

There are several methods you will use when working with JCheckBox. Some of them
are given below:
Icon getIcon() – retrives icon associated with the check box.
String getText() – retrives text associated with the check box.
void setIcon(Icon icon) – sets icon as its label.
void setText(String text) – sets text as its label.
void setSelected(boolean state) - if state is true, the check box is checked; otherwise it is
cleared.
boolean isSelected() – retrieves state (true or false) of the check box.
Radio Buttons
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often
called radio buttons. Radio buttons are supported by JRadioButton class. Several of its
constructors are shown here:
JRadioButton()
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button and s is the text specified. If state is true, the button is
initially selected. Otherwise, it is not. You can use all the above methods discussed with
check boxes for radio buttons.
Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time. The ButtonGroup class is instantiated to create a button
group. Its default constructor [ButtonGroup()] is invoked for this purpose. Elements are
then added to the button group via the following method void add(AbstractButton ab).
For example,
JRadioButton rb1 = new JRadioButton("A");
JRadioButton rb2 = new JRadioButton("B");
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);

Layout Managers
A layout manager automatically arranges your controls within a window by using some
type of algorithm. The layout manager is set by the setLayout() method. If no call to set-
Layout() is made, then the default layout manager is used. The setLayout() method has
the following general form:
void setLayout(LayoutManager layoutObj)

Advanced Java6 programming


Compiled by: Ramesh Bhatta Page 7

Here, layoutObj is a reference to the desired layout manager. Java has several predefined
layout manager classes. Some of them are described below. You can use the layout man-
ager that best fits your application.
FlowLayout
It is the default layout manager. FlowLayout implements a simple layout style, which is
similar to how words flow in a text editor. Components are laid out from the upper left
corner, left to right, and top to bottom. When no more components fit on a line, the next
one appears on the next line. A small is left between each component, above and below,
as well as left and right. Here are the constructors for FlowLayout:
FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels
of space between each component. For example,
setLayout(new FlowLayout());
The second form lets you specify how each line is aligned. Valid values for how are:
FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT, FlowLayout.LEAD-
ING, and FlowLayout.TRAILING. For example,
setLayout(new FlowLayout(FlowLayout.LEFT));
The third constructor allows you to specify the horizontal and vertical space left between
components in horz and vert respectively. For example,
setLayout(new FlowLayout(FlowLayout.LEFT,20,30));

BorderLayout
It has four narrow, fixed-width components at the edges and one large area in the center.
The four sides are referenced to as north, south, east, and west. The middle area is called
the center. Here are the constructors defined by BorderLayout:
BorderLayout() – creates a default border layout.
BorderLayout(int horz, int vert) – allows you to specify the horizontal and vertical space
left between components in horz and vert, respectively.
BorderLayout defines four constants that specify regions: BorderLayout.CENTER, Bor-
derLayout.EAST, BorderLayout.NORTH, BorderLayout.SOUTH, and BorderLay-
out.WEST.
When adding components, we will use these constants with the following form of add().
void add(Component compObj, Object region)
For example,
getContentPane().add(label,BorderLayout.NORTH);

GridLayout
It lays out components in a two-dimensional grid. The constructors supported by Grid-
Layout are:
GridLayout() – creates a single-column grid layout.

Advanced Java7 programming


Compiled by: Ramesh Bhatta Page 8

GridLayout(int numRows, int numCols) – creates a grid layout with the specified number
of rows and columns.
GridLayout(int numRows, int numCols, int horz, int vert) – also allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimited length columns and specifying numColumns as zero allows for unlimited
length rows. Components are added from first row to last row and first column to last col-
umn.
Using Insets
Sometimes you will want to leave a small amount of space between the container that
holds your components and the window that contains it. To do this, override the
getInsets() method that is defined by Container. This function returns an Insets object
that contains the top, bottom, left, and right inset to be used when the container is dis-
played. The constructor for Insets is shown here:
Insets(int top, int left, int bottom, int right)
The values passed in top, left, bottom, and right specify the amount of space between the
container and its enclosing window. The getInsets() method has this general form:
Insets getInsets()
When overriding this method, we must return a new Insets object that contains the inset
spacing you desire. For example,
public Insets getInsets() {
return new Insets(10,10,20,30);
}

Handling Events
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events. This concept
is quite simple: a source generates an event and sends it to one or more listeners. The lis-
tener simply waits until it receives an event. Once an event is received, the listener pro -
cesses the event and then returns.
In order to receive an event notification, listeners must register with an event source.
Hence, notifications are sent only to listeners that want to receive them.

Advanced Java8 programming


Compiled by: Ramesh Bhatta Page 9

Events
In the delegation model, an event is an object that describes a state change in a source. It
can be generated as a consequence of a person interacting with the elements in a graphi-
cal user interface. 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, clicking the
mouse etc. Events may also occur that are not directly caused by interactions with a user
interface. For example, an event may be generated when a timer expires, a counter ex-
ceeds a value, software or hardware failure occurs, or an operation is completed.
At the root of the Java event class hierarchy is EventObject class which is the super-
class for all event classes. AWTEvent, a subclass of EventObject, is a superclass of all
AWT events that are handled by the delegation model. The table below lists the most im -
portant of these event classes and provides a brief description of when they are generated.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked,
or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized, or be-
comes visible.
ContainerEvent Generated when a component is added to or removed from a con-
tainer.
FocusEvent Generated when a component gains or losses keyboard focus.
ItemEvent Generated when a check box or list item is clicked; also occurs
when a choice selection is made or a checkable menu item is se-
lected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed,
or released; also generated when the muse enters or exits a com-
ponent.
MouseWheelEvent Generated when the mouse wheel is moved.
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, de-
iconified, iconified, opened, or quit.

Event Sources
A source is an object that generates an event. This occurs when the internal state of that
object changes in some way. Sources may generate more than one type of event. The ta-
ble below lists some of the event sources that can generate events.
Event Source Description
Button Generates action events when button is pressed.
Checkbox Generates item events when the check box is selected or dese-
lected.
Choice Generates item events when the choice is changed
List Generates action events when an item is double-clicked; gener-

Advanced Java9 programming


Compiled by: Ramesh Bhatta Page 10

ates item events when an item is selected or deselected.


Menu Item Generates action events when a menu item is selected; generates
item events when a checkable menu item is selected or dese-
lected.
Scrollbar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed, de-
activated, deiconified, iconified, opened, or quit.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event. We use addTypeListener(TypeListener el) method for this regis-
tration. 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( ).
A source must also provide a method that allows a listener to unregister an interest in
a specific type of event. We use removeTypeListener(TypeListener el) for this unregis-
tration. Here, Type is the name of the event, and el is a reference to the event listener. For
example, to remove a keyboard listener, we use removeKeyListener( ) method.
Event Listeners
To react to an event, we implement appropriate event listener interfaces. A listener is an
object that is notified when an event occurs. It has two major requirements. First, it must
have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifica-
tions. The event listener interfaces and their corresponding method declarations are given
below.
Interface Description
ActionListener Declares one method to receive action events. Action events are
generated when a button is pressed.
void actionPerformed(ActionEvent ae)
AdjustmentListener Declares one method to receive adjustment events. Adjustment
events are generated when a scrollbar is manipulated.
void adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener Declares four methods to recognize when a component is hid-
den, moved, resized, or shown.
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListener Declares two methods to recognize when a component is added
to or removed from a container.
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
FocusListener Defines two methods to recognize when a component gains or
loses keyboard focus.
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)

Advanced Java
10programming
Compiled by: Ramesh Bhatta Page 11

ItemListener Defines one method to recognize when a check box or list item
is clicked, when a choice selection is made, or when a checkable
menu item is selected or disselected.
void itemStateChanged(ItemEvent ie)
KeyListener Defines three methods to recognize when a key is presses, re-
leased, or typed.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Defines five methods to recognize when the mouse is clicked,
enters a component, exits a component, is pressed, or is re-
leased.
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MoseWheelListener Defines one method to recognize when the mouse wheel is
moved.
void mouseWheelMoved(MouseWheelEvent mwe)
TextListener Defines one method to recognize when a text value changes.
void textChanged(TextEvent te)
WindowFocusListener Defines two methods to recognize when a window gains or
looses input focus.
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
WindowListener Defines seven methods to recognize when a window is acti-
vated, closed, deactivated, deiconified, iconified, opened, or
quit.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

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

Advanced Java
11programming
Compiled by: Ramesh Bhatta Page 12

import java.awt.event.*;
public class SwingExample extends JFrame implements ActionLis-
tener {
private JTextField t1, t2, t3;
public SwingExample() {
super("SwingExample");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l1 = new JLabel("First Value:");
JLabel l2 = new JLabel("Second Value:");
JLabel l3 = new JLabel("Result:");
t1 = new JTextField(8);
t2 = new JTextField(8);
t3 = new JTextField(8);
JButton b1 = new JButton("Add");
JButton b2 = new JButton("Subtract");
b1.addActionListener(this);
b2.addActionListener(this);
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.LEFT));
cp.add(l1);
cp.add(t1);
cp.add(l2);
cp.add(t2);
cp.add(b1);
cp.add(b2);
cp.add(l3);
cp.add(t3);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String s1, s2, s;
int x, y, z;
s1 = t1.getText();
s2 = t2.getText();
if(s1.equals(""))
x = 0;
else
x = Integer.parseInt(s1);
if(s2.equals(""))
y = 0;
else
y = Integer.parseInt(s2);
if(ae.getActionCommand() == "Add")
z = x + y;
else
z = x - y;
s = String.valueOf(z);
t3.setText(s);
}

Advanced Java
12programming
Compiled by: Ramesh Bhatta Page 13

public class MainProgram {


public static void main(String[] args) {
SwingExample se = new SwingExample();

}
}

Applets
Applet is a Java program that runs in the applet viewer or web browser that supports
Java. The main difference between normal Java applications and applets is that in applet
there is no main method unlike the standalone applications in Java.
We can embed applets into Web pages in two ways. One, we can write our own ap-
plets and embed them into Web pages. Second, we can download an applet from a remote
computer system and then embed it into a Web page.
An applet developed locally and stored in a local system is known as a local applet.
A remote applet is that which is developed by someone else and stored on a remote
computer connected to the Internet. If our system is connected to the Internet, we can
download the remote applet onto our system and run it.
Every applet in Java that uses swing components is implemented by creating a sub-
class of the JApplet class. It is the extended version of java.applet.Applet that adds sup-
port for the swing components. The following diagram shows the inheritance hierarchy of
the JApplet class.

Java.lang.Object

Java.awt.Component

Java.awt.Container

Java.awt.Panel

Java.applet.Applet

Javax.swing.JApplet

How Applets Differ from Applications


Although both applets and applications are Java programs, there are significant differ-
ences between them.

Advanced Java
13programming
Compiled by: Ramesh Bhatta Page 14

 Applets do not use the main( ) method for initiating the execution of the code. Ap-
plets when loaded, automatically call certain methods of Applet class to start and ex-
ecute the applet code.
 Unlike standalone applications, applets cannot be 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 libraries from other languages such as C or C++.

Some Useful Methods


Method Description
void destroy( ) Called by the browser just before an applet is termi-
nated. Your applet will override this method if it
needs to perform any cleanup prior to its destruc-
tion.
void init( ) Called when an applet begins execution. It is the
first method called for any applet.
boolean isActive( ) Returns true if the applet has been started. It returns
false if the applet has been stopped.
static final AudioClip Returns an AudioClip object that encapsulates the
newAudioClip(URL url) audio found at the location specified by url.
void play(URL url) If an audio clip is found at the location specified by
url, the clip is played.
void resize(int width, int height) Resizes the applet according to the dimensions
specified by width and height.
void showStatus(String str) Displays str in the status window of the browser or
applet viewer. If the browser does not support a sta-
tus window, then no action takes place.
void start( ) Called by the browser when an applet should start
(or resume) execution. It is automatically called af-
ter init( ) when an applet first begins.
void stop( ) Called by the browser to suspend execution of the
applet. Once stopped, an applet is restarted when
the browser calls start( ).

Applet Lifecycle

Advanced Java
14programming
Compiled by: Ramesh Bhatta Page 15

Every Java applet inherits a set of default behaviors from the JApplet class. These
behaviors are described below:
Loading the Applet
This phase creates an instance of the applet, initializes the applet and starts running. Re-
member two methods: init( ) and start( ).
Leaving and Returning to the Applet's Page
When the user leaves the page the browser stops the applet. When the user returns to the
page, the browser starts the applet. So is true for minimize and maximize. Remember
methods stop( ) and start( ).
Reloading the Applet
Some browsers let the user reload applets, which consists of unloading the applet and
then loading it again. Before an applet is unloaded, it's given the chance to stop itself and
then to perform a final cleanup, so that the applet can release any resources it holds. After
that, the applet is unloaded and then loaded again.
Quitting the Browser
When the user quits the browser the applet stops and frees up the resources it has held.
Remember the methods: stop( ) and destroy( ).
The applet is loaded, started, stopped and destroyed. These four processes define the life
cycle of an applet. Here are the descriptions of the methods.
 init: This method called at the initialization of the applet and called automatically
only once.
 start: This method is automatically called after init method. It is also called whenever
user returns to the page containing the applet after visiting other pages.
 stop: This method is automatically called whenever the user moves away from the
page containing applets.
 destroy: This method is called when the browser shuts down normally and it is called
only once.

Advanced Java
15programming
Compiled by: Ramesh Bhatta Page 16

Fig: An Applet’s State Transition Diagram

Creating an Executable Applet


Writing a Java Applet
1. import javax.swing.*;
2. import java.awt.*;
3. public class AppletDemo extends JApplet {
4. private String str;
5. public void init() {
6. str = "Initialized...";
7. }
8. public void start() {
9. str = str + "Started...";
10. }
11. public void stop() {
12. str = str + "Stopped...";
13. }

Advanced Java
16programming
Compiled by: Ramesh Bhatta Page 17

14. public void destroy() {


15. System.out.println("Destroyed...");
16. }
17. public void paint(Graphics g) {
18. g.drawString(str, 5, 15);
19. }
20. }
Save above code as the file AppletDemo.java. The above applet is compiled as of appli-
cation using javac tool. This creates the .class file named AppletDemo.class.
Running an Applet
There are two ways of running the applet. The first one is to execute the applet within the
java compatible web browsers. The second way is using the tool appletviewer. Regard-
less of the above method you must write a short HTML file as follows:
<applet code = “AppletDemo” width = 200 height = 100>
</applet>
You can save the HTML file as name of your choice (say fisrtapplet.html).
Now give the command appletviewer firstapplet.html and see the result.
Understanding the Code
Lines 1 and 2: import statements
Here in our applet we are importing classes from packages javax.swing and java.awt.
javax.swing.*; and java.awt.*;
It is important here to understand is that we have importing all the classes from packages
javax.swing (contains the class required for applet called JApplet) and java.awt (contains
the classes required for GUI, and other windowing functions, here the class Graphics is
from awt).
Line 3: public class AppletDemo extends JApplet
Remember this class is accessed by code outside the program so public must be there. All
the parts in this section are same as of the application shown previously.
Lines 4 – 16: already discussed
Line 17: public void paint(Graphics g)
Unlike the java application, applet does not require main method. However in applet
there are various methods that are called automatically and one of them is paint method.
The method paint is overridden by the applet. This method is called by the applet each
time when the applet is started. The parameter in this method is of the type Graphics
which is the class defined in awt package.
Line 7: g.drawString(str, 20, 30);
The Graphics class has the method named drawString with the parameters as string to be
displayed, and coordinate position of the string.

Advanced Java
17programming
Compiled by: Ramesh Bhatta Page 18

Applet Example with Swing Components and Event


Handling
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AppletExample extends JApplet implements Ac-
tionListener {
private JTextField t1, t2, t3;
public void init() {
JLabel l1 = new JLabel("First Value:");
JLabel l2 = new JLabel("Second Value:");
JLabel l3 = new JLabel("Result:");
t1 = new JTextField(8);
t2 = new JTextField(8);
t3 = new JTextField(8);
JButton b1 = new JButton("Add");
JButton b2 = new JButton("Subtract");
b1.addActionListener(this);
b2.addActionListener(this);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b2);
add(l3);
add(t3);
}
public void actionPerformed(ActionEvent ae) {
String s1, s2, s;
int x, y, z;
s1 = t1.getText();
s2 = t2.getText();
if(s1.equals(""))
x = 0;
else
x = Integer.parseInt(s1);
if(s2.equals(""))
y = 0;
else
y = Integer.parseInt(s2);
if(ae.getActionCommand() == "Add")
z = x + y;

Advanced Java
18programming
Compiled by: Ramesh Bhatta Page 19

else
z = x - y;
s = String.valueOf(z);
t3.setText(s);
}
}

Security Restrictions
The implementation of the security policies differs from browser to browser. Also,
security policies are subject to change. Current browsers impose the following
restrictions on any applet that is loaded over the network:
 An applet cannot load libraries or define native methods.
 It cannot ordinarily read or write files on the host that's executing it.
 It cannot make network connections except to the host that it came from.
 It cannot start any program on the host that's executing it.
 It cannot read certain system properties.

Applet Capabilities
Applets possess some capabilities that applications do not have. Here are some other
things that current browsers and other applet viewers let applets do:
 Applets can usually make network connections to the host they came from.
 Applets running within a Web browser can easily cause HTML documents to be dis-
played.
 Applets can invoke public methods of other applets on the same page.
 Applets that are loaded from the local file system (from a directory in the user's
CLASSPATH) have none of the restrictions that applets loaded over the network do.

Advanced Java
19programming

You might also like