Distributed Programming

in Java

Distributed Programming in Java
Learner’s Guide
© 2014 Aptech Limited
All rights reserved.
No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.
All trademarks acknowledged.

APTECH LIMITED

E-mail: ov-support@onlinevarsity.com
First Edition - 2014

Dear Learner,
We congratulate you on your decision to pursue an Aptech course.
Aptech Ltd. designs its courses using a sound instructional design model – from conceptualization
to execution, incorporating the following key aspects:

Scanning the user system and needs assessment
Needs assessment is carried out to find the educational and training needs of the learner
Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG*
analyzes these on a monthly basis to understand the emerging technology training needs for
the Industry.
An annual Industry Recruitment Profile Survey# is conducted during August - October
to understand the technologies that Industries would be adapting in the next 2 to 3 years.
An analysis of these trends & recruitment needs is then carried out to understand the skill
requirements for different roles & career opportunities.
The skill requirements are then mapped with the learner profile (user system) to derive the
Learning objectives for the different roles.


Needs analysis and design of curriculum
The Learning objectives are then analyzed and translated into learning tasks. Each learning
task or activity is analyzed in terms of knowledge, skills and attitudes that are required to
perform that task. Teachers and domain experts do this jointly. These are then grouped in
clusters to form the subjects to be covered by the curriculum.
In addition, the society, the teachers, and the industry expect certain knowledge and skills
that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving,
positive attitude etc. These competencies would cover both cognitive and affective domains.
A precedence diagram for the subjects is drawn where the prerequisites for each
subject are graphically illustrated. The number of levels in this diagram is determined
by the duration of the course in terms of number of semesters etc. Using the precedence
diagram and the time duration for each subject, the curriculum is organized.

Design & development of instructional materials
The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identified.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.

The detailed instructional material – Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.

Strategies for delivery of instruction
Careful consideration is given for the integral development of abilities like thinking, problem
solving, learning-to-learn etc. by selecting appropriate instructional strategies (training
methodology), instructional activities and instructional materials.
The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the
instructional process by specially including creative activities with group interaction between
the students and the trainer. The positive aspects of web based learning –acquiring information,
organizing information and acting on the basis of insufficient information are some of the
aspects, which are incorporated, in the instructional process.


Assessment of learning
The learning is assessed through different modes – tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defined by the
learning objectives.


Evaluation of instructional process and instructional materials
The instructional process is backed by an elaborate monitoring system to evaluate - on-time
delivery, understanding of a subject module, ability of the instructor to impart learning. As an
integral part of this process, we request you to kindly send us your feedback in the reply prepaid form appended at the end of each module.

*TAG – Technology & Academics Group comprises members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software
Majors & representatives from regulatory organizations/forums.
Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology
trends. The group interfaces with the representatives of the TAG thrice a year to review and
validate the technology and academic directions and endeavors of Aptech Ltd.

Aptech New Products Design Model
Key Aspects

1

Evaluation of
Instructional
Processes and
Material

Scanning the user
system and needs
assessment

2

Need Analysis
and design of
curriculum

3

Design and
development of
instructional
material

Assessment of
learning

4

Strategies for
delivery of
instructions

5

6

Preface
The book, Distributed Programming in Java, aims to teach the students the advanced concepts of Java
required for distributed computing, such as Swing, internationalization, networking, Remote Method
Invocation (RMI), and JavaMail. The book also provides technical overview of the new features introduced
in Java SE 7 for the Swing and Networking Application Programming Interfaces (APIs).
Java SE 7 added several new features that enable programmers to write resilient, reliable, and nimble
code. The book provides information on the new features introduced in Swing such as Pluggable Look
and Feel, JTable sorting and filtering, JTextComponent printing, JLayer class. It also introduces decorating
windows with translucent and non-rectangular shapes. Further, the book also discusses the enhancement
in the networking and RMI APIs. Finally, the book introduces JavaMail API that provides standard interface
for sending and receiving mails for different protocols.
This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring
you the best and the latest in Information Technology. The process of design has been a part of the ISO
9001 certification for Aptech-IT Division, Education Support Services. As part of Aptech’s quality drive,
this team does intensive research and curriculum enrichment to keep it in line with industry trends.
We will be glad to receive your suggestions.

Design Team

Nothing is a waste of time if you
use the experience wisely

Table of Contents

Sessions
1.

Introduction to Swing

2.

Basic Swing Components

3.

Layout Managers

4.

Menu Components

5.

Lists and Panes

6.

Advanced Swing Components

7.

Internationalization

8.

Networking

9.

Remote Method Invocation

10.

JavaMail

Session 1
Introduction to Swing
Welcome to the Session, Introduction to Swing.
This session introduces the Java Foundation Classes (JFC) and Swing. The
session explains the Swing architecture that help users to create efficient
Graphic User Interface (GUI) programs. The session introduces different
types of components in Swing. Further, the session explains how to create
Swing applications in NetBeans Integrated Development Environment
(IDE). Finally, the session concludes with the explanation on concurrency
support in Swing.
In this Session, you will learn to:
 Explain JFC and Swing
 Explain AWT
 State the benefits of using Swing over AWT
 Explain MVC architecture
 Describe Separable Model Architecture
 Describe container and state its needs
 Describe JFrame class and its methods
 Explain JApplet class and its methods
 Describe JPanel class and its methods to create and display it
 Describe and explain various lightweight components
 Describe the steps to create Swing application in NetBeans IDE
 Explain concurrency in Swing

Session

1
Introduction to Swing

1.1 Introduction
Swing is a Java Graphical User Interface (GUI) library released with Java version 2 by Sun Microsystems. It
is an extension to Abstract Window Toolkit (AWT) Application Programming Interface (API) which enables
creation of platform-specific components in Java. The main advantage of Swing API is that it provides
lightweight GUI components that are not dependent on the native platform for their look and feel.
Apart from extending the AWT components, the Swing API also supports complex components that helps
to create more powerful and interactive GUI applications.

1.1.1 Java Foundation Classes (JFC)
Starting with Java Development Kit (JDK) 2.0, the JFC was introduced in Java. JFC is a graphical framework
which includes the Swing GUI components, pluggable look and feel support, Java 2D APIs, Drag and Drop
API, accessibility APIs, and internationalization.
Together, they provide a consistent User Interface (UI) for Java programs, regardless of whether the
underlying Operating System (OS) used is Windows, Macintosh, or Linux.
Figure 1.1 displays the JFC framework.

Figure 1.1: JFC Framework
Table 1.1 lists the JFC features and their description.

Concepts

Feature
Swing GUI Components

Pluggable Look-and-Feel

Description
Contains all type of components, such as buttons
to split panes to tables. Some components also
support features, such as sorting, printing, and
drag and drop.
Allows a choice of look and feel and supports the
GTK + Look and Feel.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Feature
Accessibility API

Java 2D API
Internationalization

Description
Allows User Interface (UI) to interact with different
products, such as screen readers and Braille
displays.
Supports high-quality 2D graphics, text, and images
to be developed in Java applications.
Allows to develop applications that allow
interactions in different languages.
Table 1.1: JFC Features

1.1.2 Abstract Window Toolkit (AWT)
In the initial version of Java, AWT was the only library available to develop Graphical User Interface (GUI)
applications. This toolkit contained the classes to represent components, such as Button, CheckBox,
TextField, and so on to create a GUI based standalone application or an applet. The AWT components
were based on peer-components. The peer-components are platform specific components offered by the
underling Operating System (OS).

Figure 1.2: Java Applet with AWT Components
Note: An applet is a Java program which runs as part of a Web page. The applets can be tested in a
standalone application named AppletViewer provided in JDK, before adding them to a Web page.

V 1.0 © Aptech Limited

Concepts

Figure 1.2 displays the AWT components added in a Java Applet.

Session

1
Introduction to Swing

The peer-component dependency made the AWT components heavy as far as memory consumption and
operational performance was considered. Hence, they were referred to as heavy-weight components.
The rendering (drawing) of the actual component in an application was achieved by the native-code
languages C/C++ and not directly by Java.
AWT components would always have the ‘look and feel’ of the native components. For example, on a
Linux OS, an AWT-based Java application would have a different look and feel than the one on a Windows
OS.
Figure 1.3 displays the platform-specific implementation of AWT component.

Figure 1.3: Platform-specific Implementation of AWT Component

1.1.3 Swing

Concepts

Swing is a framework based on the Model-View-Component (MVC) architecture as compared to AWT
which was just a toolkit. Swing supports a technology called ‘Pluggable-Look-And-Feel’ (PLAF) where
components can be displayed as on any OS. In other words, on a Linux OS, a button can be shown as it
looks on a Windows OS.
Swing components are lightweight and visually appealing as compared to AWT components. Swing helps
to specify the look and feel of the program’s GUI needs. In contrast, AWT components always inherit the
look and feel of the native platform, on which they are currently running. PLAF allows adapting the look
and feel of any OS system across any platform.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.4 displays the look and feel of Swing components on different platforms.

Figure 1.4: Swing Components Look and Feel

1.1.4 Capabilities of Swing Components
Swing components have more capabilities than AWT components. Some of these are as follows:
Swing Buttons and Labels can display images in addition to textual labels.

Borders drawn around most of the Swing components can be changed.

The behavior or appearance of a Swing component can be changed by either invoking methods on
it or by creating a subclass of it.

Swing components do not have to be rectangular. For example, Buttons can be round.

Swing is based on the MVC architecture that offers a very streamlined way of representing and
performing the components functionality.

Concepts

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Figure 1.5 displays the different types of Swing components.

Figure 1.5: Swing Components

1.2 Swing MVC Architecture
MVC is a method of separating the visual, interaction, and data components. MVC makes it very easy to
have multiple displays of the same information. It essentially provides greater control over the UI and its
behavior.
MVC is an object-oriented UI design pattern first introduced in Smalltalk in the late 1970s. It helps to
decouple data access and business logic from the manner in which it is displayed to the user.
The MVC architecture decomposes the three functionality into three distinct objects.

Concepts

Model

The Model represents all the data and the various states of the component. Data is provided by the
user. The component will be in various states because of user interaction. The information about
these states will be maintained in the Model.
A Model may be responsible for indirect communication with the View and the Controller. By
indirect it means that the Model does not know its View and Controller. Instead, the Model sends
out notifications or broadcasts known as events.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

View

The View depicts the graphical part on the screen. It takes the data and various states from the
Model to render the component’s graphical part.
The View determines the visual representation of the components Model. This is a component’s
‘look and feel’. The View is responsible for keeping it’s on-screen representation updated and may
do so upon receiving indirect messages from the Model, or direct messages from the Controller.

Controller

The Controller is responsible for determining whether the component should react to any input
events from input devices such as the keyboard or mouse. The Controller determines what actions
are performed when the component is used. The Controller can receive direct messages from the
View and indirect messages from the Model.
In this way, a Model is not bound to a specific View or Controller, allowing us to have several Views
and Controller’s manipulating a single Model.
Figure 1.6 displays the MVC architecture.

1.2.1 Swing Separable Model Architecture
Almost all modern UI frameworks combine the View and Controller, whether they are based on Smalltalk,
C++, or Java Swing.
JFC Swing is the newest addition to this group. Swing packages each component’s View and Controller
into an object called as UI delegate. For this reason, Swing’s underlying architecture is more accurately
referred to as Separable Model architecture or the Model-Delegate architecture, rather than ModelView-Controller architecture.

V 1.0 © Aptech Limited

Concepts

Figure 1.6: MVC Architecture

Session

1
Introduction to Swing

Swing uses a variant of the MVC architecture where it combines the view and the controller into a single
unit called UI delegate. This UI delegate is responsible to propagate events generated through user
interaction to the model.
Ideally communication between both the Model and the UI Delegate is indirect, allowing more than one
Model to be associated with one UI Delegate, and vice versa.

1.2.2 Swing Packages in Java SE 7
Swing API provides a main package named javax.swing. This package provides basic Swing components
such as buttons, labels, text boxes, dialog boxes, and so on and needs to be imported in the Java
application.
The javax.swing package contains various sub-packages that provide specific functionality for the
components. Some of the sub-packages provided in Java SE 7 are as follows:

javax.swing,event - Provides classes and interfaces for handling events triggered on Swing

components.

javax.swing.plaf - Provides functionality to handle look and feel of the Swing components.
This package provides further sub-packages, such as javax.swing.plaf.basic, javax.swing.
plaf.metal, javax.swing.plaf.nimbus, and so on.

javax.swing.text - Provides classes to deal with editable and noneditable components. This
package provides further sub-packages such as javax.swing.text.html and javax.swing.
text.rtf.

javax.swing.JTable - Provides classes and interfaces to work with the table of rows and

columns.

javax.swing.JTree - Provides classes and interfaces to work with the tree structure of

Concepts

hierarchical data.

javax.swing.filechooser - Provides classes to work with file dialog box.

javax.swing.undo - Provides functionality such as undo or redo for editable text components.

1.2.3 Swing Components Look and Feel
Swing offers a host of look and feel for its components and it differs from one operating system to
another. The default look and feel in JDK 1.2 was the Metal Look and Feel. To leverage the cross-platform,
capabilities of the Java platform, two new look and feel were introduced in JDK 1.5.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

The brief description of these look and feel is as follows:

GTK+

JDK 1.4.2 introduced two new Look and Feel’s - GTK+ and Microsoft Windows XP. The method
of UIManager.setLookAndFeel() specifies GTK+ Look and Feel as shown in the following
statement:
UIManager.setLookAndFeel(“com.sun.java.swing.plaf.gtk.GTKLookAndFeel”);

The class GTKLookAndFeel implements GTK+ Look and Feel which is based on GTK+ 2.0. The GTK
Look and Feel was introduced in Linux. This new Look and Feel can be customized by using resource
files. The resource file contains styles for Swing components. GTK provides mechanism for picking
up themes and making changes to UI components at runtime.

Synth

Java Platform, Standard Edition 2.0 (J2SE) release 5.0 introduced a new Look and Feel, called
Synth. It allows you to programmatically load an XML file containing properties of particular Swing
component, such as font, color, border, and so on. This allows changing Look and Feel of a Swing
component at runtime.

1.2.4 UIManager Class
The javax.swing.UIManager class is used to set and retrieve the current Look and Feel of the GUI
components. The UIManager has methods to set and get the Look and Feel.
Table 1.2 lists the UIManager methods.
setLookAndFeel(String className)

Description

The method sets the current Look and Feel
using a Look and Feel object specified in the
className.
LookAndFeel getLookAndFeel()
The method returns the current default Look
and Feel or null.
String
The method returns the class name of the native
systems Look and Feel if it exists or the name of
getSystemLookAndFeelClassName()
the default cross-platform Look and Feel.
String
The method returns the class name of the
getCrossPlatformLookAndFeelClassName() default cross-platform Look and Feel which is
the Java Look and Feel.
Table 1.2: Methods to set and get the Look and Feel

V 1.0 © Aptech Limited

Concepts

Method

1

Session

Introduction to Swing

1.2.5 Nimbus Pluggable L&F
Nimbus is a polished cross-platform look and feel introduced in the Java SE 6 Update 10 (6u10) release.
Nimbus uses Java 2D vector graphics to draw the UI, rather than static bitmaps, so the UI can be crisply
rendered at any resolution. Nimbus is highly customizable.
The nimbus pluggable look and feel can be activated in three ways:

Add the code to the event-dispatching thread before creating the GUI.

Specify Nimbus as the default look and feel for a particular application at the command line, as
follows:
java -Dswing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel MyApp

Permanently set the default look and feel to Nimbus by adding the following line to the <JAVA _
HOME>/lib/swing.properties file:
swing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel

Code Snippet 1 shows how to enable the Nimbus Look and Feel.
Code Snippet 1:
import javax.swing.UIManager.*;
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (“Nimbus”.equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.

Concepts

}

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.7 shows a Nimbus Look and Feel.

Figure 1.7: Nimbus Look and Feel

1.2.6 Classes and Interfaces to Implement Look and Feel
The javax.swing and javax.swing.plaf packages have the required classes to support the Look
and Feel. Additional classes required are available in non standard packages. The javax.swing package
has the following classes to implement the Look and Feel:

The LookAndFeel class

The LookAndFeel class completely characterizes the Look and Feel of a component. The
LookAndFeel class is an abstract class. The 4523 package provides a concrete implementation
class BasicLookAndFeel. This class cannot be instantiated. The javax.swing.plaf.metal.
MetalLookAndFeel class provides the default Look and Feel. The javax.swing.plaf.metal.
MetalLookAndFeel extends the BasicLookAndFeel class. The javax.swing.plaf.multi.
MultiLookAndFeel class allows multiple user interfaces to be associated with a component at
the same time.

Swing provides three Look and Feel, Metal, and two Look and Feel which characterize the Look and Feel
of Windows and Motif (Unix/X). A Look and Feel which characterizes the Macintosh is available as a
separate downloadable package.
The Windows Look and Feel is restricted for use only on the Windows OS for copyright reasons.

V 1.0 © Aptech Limited

Concepts

1.2.7 Dependencies of Look and Feel on Operating System

Session

1
Introduction to Swing

1.2.8 Setting and Retrieving Look and Feel
The setLookAndFeel() method of the javax.swing.UIManager is used to set the Look and Feel.
The Look and Feel implementation class for Windows and Motif are available in a non-standard package,
and not in the core Swing package.
The WindowsLookAndFeel is available in the com.sun.java.swing.plaf.windows package.
The MotifLookAndFeel is available in the com.sun.java.swing.plaf.motif package.
Code Snippet 2 demonstrates how to set the classic Windows Look and Feel.
Code Snippet 2:
try {
UIManager.setLookAndFeel(“com.sun.java.swing.plaf.windows.
WindowsLookAndFeel”);
} catch(ClassNotFoundException ex) {
System.out.println(“Exception : ” +
ex.getMessage());
} catch(UnsupportedLookAndFeelException ex){
System.out.println(“Exception : ” +
ex.getMessage());
}

1.3 Overview of Container
The javax.swing package provides two type of GUI components namely components and containers.
The components are stand-alone visual controls whereas a container is a visual GUI window that is used
to hold Java components.
There are three types of containers in Swing.

Concepts

With the exception of top-level containers, all Swing components whose names begin with ‘J’ descend
from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit from
JComponent. However, JFrame and JDialog don’t because they implement top-level containers.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.8 shows the componenty hierarchy of javax.swing package.

Figure 1.8: Component Hierarchy in javax.swing Package
Table 1.3 shows the types of containers available in Swing API.

Type of Container
Top Level Containers

General purpose Containers
Special Purpose containers

Examples

JApplet,
JFrame

JDialog, One

Description

of these components
must be present in any swing
application. They form the root
of any container hierarchy.
JPanel,
JscrollPane, These are present in most swing
JTabbedPane, JToolBar
applications.
J I n t e r n a l F r a m e , These play specific roles in the
JLayeredPane, JRootPane
UI.

Concepts

Table 1.3: Types of Containers

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Figure 1.9 displays the container components.

Figure 1.9: Container Components

1.3.1 Root Pane
The root pane has four parts Glass Pane, Layered Pane, Content Pane, and Menu Bar.

Glass Pane

A glass pane is hidden by default. If the glass pane is made visible, then it’s such as a sheet of glass
over all the other parts of the root pane. It’s completely transparent unless one implements the
glass pane’s paintComponent() method so that it displays something.

Layered Pane

The layered pane serves to position its contents, which consist of the content pane and the optional
menu bar. It can also hold other components in a specified Z-order.

Concepts

Each root pane places its menu bar and content pane in an instance of JLayeredPane. The Z
ordering that the layered pane provides enables behavior such as displaying popup menus above
other components.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.10 displays the layered pane.

Figure 1.10: Layered Pane

Content Pane

The content pane is the container of the root pane’s visible components. Most GUI components
are added to this content pane.
The default content pane is a simple intermediate container that inherits from JComponent, and
uses a BorderLayout as its layout manager.
The object-reference of the content pane of a top-level container is retrieved by calling the
getContentPane() method. You then add GUI components to the content pane.

Figure 1.11: Content Pane

V 1.0 © Aptech Limited

Concepts

Figure 1.11 displays the content pane.

Session

1
Introduction to Swing

Menu Bar

All top-level containers can, in theory, have a menu bar. In practice, however, menu bars usually
appear only in JFrame and in JApplet. To add a menu bar to a top-level container, a JMenuBar
object is created, populated with menus, and then the setJMenuBar() method is invoked.
The general-purpose containers are used to add other lightweight components, such as JButton
and JTextField. Eventually the general-purpose containers are added to a top-level container.
The various general-purpose containers have different functionality depending on their use, for
example a JPanel is an intermediate container to group components.
Figure 1.12 displays the menu bar.

Figure 1.12: Menu Bar

1.3.2 JFrame
A JFrame is a top-level container used to create a GUI-based application. It is available in the javax.
swing package.
A Swing based GUI application can be developed by using two distinct approaches:

Concepts

Extending javax.swing.JFrame

You use this approach of extending JFrame class when the class is not extending from another
class. The advantages of this approach are that you can call the methods of the super class without
indirection. You can also access the instance data of the application, without specifying them as
static.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Code Snippet 3 displays the use of JFrame class.
Code Snippet 3:
import javax.swing.*;
public class WinApp extends SomeOtherClass
{
// Instance Data
. ..
public static void main(String[] args)
{
JFrame frame = new JFrame();
...
}
}

Declaring javax.swing.JFrame

When the application is already extending another class, you cannot extend from javax.swing.
JFrame class. In such cases, an object of the javax.swing.JFrame class is declared in the
application.
Code Snippet 4 displays the creation of an object of JFrame class.
Code Snippet 4:
import javax.swing.*;
public class WinApp extends SomeOtherClass
{
// Instance Data
. . .
public static void main(String[] args)
JFrame frame = new JFrame();
. . .
. . .
}
}

V 1.0 © Aptech Limited

Concepts

{

Session

1
Introduction to Swing

A programmer cannot add components to the JFrame directly. The components are added to
the content pane of the JFrame. However, in JDK 1.5 and later versions, the compiler converts
statements such as add(component) to getContentPane().add(component) during
compilation. Though this is a convenient way to add components, it should be avoided for two
reasons, first the program is not backward compatible, and second it is a waste of time invoking
the getContentPane() method for each component. The preferred way is to retrieve the object
reference and use this reference to add each component.

1.3.3 Creating a JFrame
There are three basic things to be carried out on a frame. You create a frame, display a frame, and close
the frame. Note that components cannot be added to the JFrame directly. They have to be added to the
content pane of JFrame.

To create a JFrame

A JFrame instance is created by using one of the following constructors:

JFrame():

Constructs a new frame that is initially invisible, with no title

JFrame(String title):

Creates a new, initially invisible frame with the specified title

To create a JFrame, you write the following code: JFrame
JFrame(“Login”);

frmWindow

=

new

This creates a frame with the title ‘Login’.

To display a JFrame

The JFrame after instantiation is not visible by default. To make it visible, the setVisible
(boolean) method is used. If Boolean value is set to true, then the JFrame is visible otherwise
not. A JFrame does not have a default initial size. You have to specify its size by invoking its
setSize()method.
The setVisible() method brings the JFrame into a realized state and hence, no components
can be added to the JFrame after this statement.

Concepts

To display a JFrame, you first set the size and then use the setVisible() method in the following
manner:
frmWindow.setSize(200,200);
frmWindow.setVisible(true);

The pack() method lays out all the component and makes the frame displayable. The pack()
method causes the window to be sized according to the preferred size and layout of its
subcomponents. The setVisible() method also displays the frame.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

An important point to note about displaying frames is some thread issues. When a Java program is
executed, the JVM starts a thread referred to as the main-thread to execute the application. This
main-thread is responsible for all aspect of the program’s execution including memory access, I/O
operations, and so on except the Swing related GUI. During program execution, when the JVM
encounters Swing related operation for the first time, it starts another thread to handle the Swing
components. This thread is referred to as the event-dispatch thread, which is responsible for all
aspect of the GUI components. These two threads can get into a dead-lock or could race for CPU
time. If such a situation occurs, the Swing based application could either crash or become nonresponsive. To avoid these problems Java provides a SwingUtilities class with a static method
invokeLater(). The method invokeLater() takes an argument of interface Runnable. The
code to be executed is provided in the run() method.
Code Snippet 5 demonstrates how to use the SwingUtilities.invokeLater() method.
Code Snippet 5:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Code to be executed
...
...
}
}

To close a JFrame

The JFrame provides three system buttons on the top-right corner, to minimize, resize, and close.
The functionality of close button is partially implemented by the JFrame class. The programmer
has to either provide a default means to close the frame or register a WindowListener interface
object to handle the close event.

By default, the close operation of the JFrame is not functional. To provide the close functionality,
you use the following method:
frmWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

V 1.0 © Aptech Limited

Concepts

One important point to note is that a Swing based application can be executed with either
java.exe or javaw.exe. Executing Swing based programs with javaw.exe is a more elegant way,
because the operating system shell is released immediately when the program executes. However,
if the close operation is not accounted for by any one of the two methods mentioned, then the JVM
will not terminate when the user exits the program. It is imminent that a few applications executed
and closed in this way will lead to memory over low error.

Session

1
Introduction to Swing

Figure 1.13 shows a JFrame created by JFrame method.

Figure 1.13: JFrame

1.3.4 JInternalFrame
JInternalFrame provides the ability to create lightweight frames that exist inside other components.
A JInternalFrame is entirely managed within another Java container allowing for frame operations
such as dragging, closing, minimize, maximize, becoming an icon, and so on. With the JInternalFrame
class, you can display a JFrame like window within another window.

The content pane of the JInternalFrame is where child components are added to a container. To add
a child component to the content pane the internalFrame.add(child) method is used.

Concepts

The most benefit of JInternalFrame is derived when added to a JDesktopPane. The UI delegates
the look-and-feel-specific actions to the DesktopManager object maintained by the JDesktopPane.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Table 1.4 lists the common constructors of JInternalFrame class.
Constructor

Description
JInternalFrame()
Constructs a JInternalFrame with no title.
J I n t e r n a l F r a m e ( S t r i n g Constructs a JInternalFrame with a specific title.

title)
J I n t e r n a l F r a m e ( S t r i n g Constructs a JInternalFrame with a title and resizability.
title, boolean resizable)
JInternalFrame(String
title, boolean resizable,
boolean closeable)
JInternalFrame(String
title, boolean resizable,
boolean closeable, boolean
maximizable)
JInternalFrame(String
title, boolean resizable,
boolean closable, boolean
maximizable,
boolean
iconifiable)

Constructs a JInternalFrame with a title, resizability, and
closability.
Constructs a JInternalFrame with a title, resizability,
closability, and maximizability.
Constructs a JInternalFrame with the specified title,
resizability, closability, maximizability, and iconifiability.

Table 1.4: Constructors of JInternalFrame
Table 1.5 lists the methods of JInternalFrame.
Method

Description
container getContentPane()
Returns the content pane for the JInternalFrame.
void addInternalFrameListener() Adds a specified internal frame listener to respond to
events.
void dispose()
This makes the internal frame invisible, unselected, and
closed.
protected
void Fires an event of the internal frame.
fireInternalFrameEvent()

Table 1.5: Methods of JInternalFrame

Concepts

The JInternalFrame can display a JFrame like window within another window. Internal frames are
added to the desktop pane, which in turn used as the content pane of a JFrame.

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Figure 1.14 shows an JInternalFrame.

Figure 1.14: JInternalFrame
Code Snippet 6 shows how to create a desktop and internal frame.
Code Snippet 6:
...
JDesktopPane desk1 = new JDesktopPane();
createInternalFrame();
setContentPane(desk1);
protected void createInternalFrame()
{
MyInternalFrame fm1 = new MyInternalFrame();
fm1.setVisible(true);
desk1.add(fm1);
...
fm1.setSelected(true);
}

Concepts

...

1.3.5 JApplet
An Applet is a Java program which is meant to run as part of a Web page. While using Swing, the javax.
applet.JApplet class is used to create an Applet. Once created this Applet is embedded in the Web
page with the <applet> tag.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Table 1.6 lists the methods of JApplet class.

Method

init()

Start()
Paint()

Stop()
Destroy()

Description
This method is used to initialize a JApplet. All the one-time
initialization code is written in this method. In the life cycle of a
JApplet, this method is called only once.
This method is invoked once after the init() method. It could be
used to start threads.
This method is called when the applet interface is to be redrawn.
The method accepts a parameter of java.awt.Graphics class.
This graphics object has several methods to draw primitive graphics
elements such as line, ellipse, arc, and so on.
This method is invoked when the user leaves the page that contained
the applet. This method can be called more than once.
When the applet is unloaded from memory, this method is invoked.
In the life-cycle of a JApplet it is invoked only once. This method
is used to free up resources such as images, network, or database
connections.
Table 1.6: Methods of JApplet

Figure 1.15 shows the method call of the JApplet class.

Figure 1.15: JApplet Class
Code Snippet 7 shows you how to create an applet by sub classing the JApplet class.
import javax.swing.JApplet;
...
public class MyApplet extends JApplet
{

V 1.0 © Aptech Limited

Concepts

Code Snippet 7:

Session

1
Introduction to Swing

public void init()
{
...
}
public void start()
{
...
}
}

1.3.6 JPanel
The JPanel class is both a container and a component. Other components such as JButton, JTextField,
and so on can be added to JPanel. JPanel in turn is added to a top-level container, or even another
JPanel for nesting purposes.
A JPanel is a rectangular opaque component, without any visible border by default. However, you can
add a border for demarcation. Several different types of borders are available. Adding components to a
JPanel first and then adding it to a top-level container is more advantageous than adding components
directly.

Concepts

Figure 1.16 displays a JPanel.

Figure 1.16: JPanel

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

A JPanel instance is created by invoking its default constructor. The default layout manager of JPanel
is FlowLayout.
By default the JPanel as a component is visible. You can make it invisible by using the
setVisible(boolean) method. If Boolean parameter is set to true, JPanel is visible else it is not
visible.
Code Snippet 8 shows how to create the JPanel instance.
Code Snippet 8:
import javax.swing.JPanel;
JPanel myPanel;
myPanel = new JPanel();
...

1.4 Lightweight Components
Swing components depend less on the target platform and use less of the native GUI resource. Hence,
the Swing components that don’t rely on native GUI are referred to as lightweight components
Swing components are referred to as lightweight components. These components do not have their
peer-components equivalent as compared to AWT components.
Lightweight components render (draw) themselves with pure Java code. They do not depend on external
native language code such as C/C++ which forms the peer equivalent.
The advantages of lightweight components are that they do not consume extra overheads in terms of
memory and execution time. They are platform independent. Their ‘Pluggable-Look-And-Feel’ capabilities
allow to virtually copy the look and feel of any operating system on other operating systems.

Concepts

Figure 1.17 displays the lightweight components.

Figure 1.17: Lightweight Components

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

1.4.1 JLabel
The JLabel is a component to display static text in a GUI-based application. It can also display an icon,
or both text and icon.
Table 1.7 lists the JLabel constructors.
JLabel()

Constructor

Description

JLabel(String label)
JLabel(ImageIcon icon)
JLabel(String label, ImageIcon icon)

Creates a label without text.
Creates a label with the specified text; where
label is a string.
Creates a label with the specified image; where
icon is an image.
Creates a label with the specified text and image;
where label is a string and icon is an image.

Table 1.7: JLabel Constructors
Figure 1.18 displays a JLabel.

Figure 1.18: JLabel
Code Snippet 9 shows how to create a label containing a caption and an image and add it to the
container.
Code Snippet 9:
// Import the JLabel and ImageIcon class

Concepts

import javax.swing.JLabel;
import javax.swing.ImageIcon;
...

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

// Create an image
ImageIcon icon = new ImageIcon(“/images/name.gif”);
// Create a label with an image in it
JLabel lblName = new JLabel(“Name”, icon);
// Add the label to a container
getContentPane().add(lblName);
...

To use the JLabel class, first you need to import it using an import statement. To display an image in
the label, first you have to create an instance of ImageIcon class. This instance will refer to a .jpeg,
.jpg, or .gif image file. In the Code Snippet, it refers to the name.gif file. Next, the ImageIcon
instance is passed as a parameter to JLabel constructor. Next, to display the label in the container, you
invoke the add() method on the content pane instance of a container such as JApplet or a JFrame.
Table 1.8 lists the two important methods of the JLabel class.

Method

Description

public String getText();
public void setText(String label);

The getText() method can be used to retrieve
the text of the JLabel.
The setText() method can be used to dynamically
change the text of a JLabel.

Table 1.8: JLabel Class Methods
Code Snippet 10 shows how to create a label and retrieve its caption.
Code Snippet 10:
// Create a label with the text “Name” in it.
JLabel lblName = new Label(“Name”);
// Retrieve the caption of lblName component
String caption = lblName.getText();

1.4.2 JButton
A JButton is a rectangular component with a text or icon as its label, and can fire an event when clicked
with a mouse.
Table 1.9 lists the constructors of the JButton.

V 1.0 © Aptech Limited

Concepts

The code retrieves the caption of the label, lblName using the getText() method and assigns it to
the variable caption. In other words, the variable caption is assigned the value “Name”.

Session

1
Introduction to Swing

JButton()

Constructor

Description

Creates a button without a label.
JButton(String label)
Creates a button with the specified label; where
label is a string.
JButton(ImageIcon icon)
Creates a button with the specified image; where
icon is an image.
JButton(String label, ImageIcon icon) Creates a button with the specified label and image;
where label is a string and icon is an image.
Table 1.9: Methods of JButton
Code Snippet 11 shows how to create a button containing a caption and an image, and add it to the
container.
Code Snippet 11:
// Import the JButton and ImageIcon class import javax.swing.JButton;
import javax.swing.ImageIcon;
...
// Create an image
ImageIcon icon = new ImageIcon(“/images/ok.gif”);
// Create a button with an image on it
JButton lblName = new JButton(“Name”, icon);
// Add the button to a container
getContentPane().add(lblName);
...

Concepts

To use the JButton class, first you need to import it using an import statement. To display an image in
the button, first you have to create an instance of ImageIcon class. This instance will refer to a .jpeg,
.jpg, or .gif image file. In the Code Snippet, it refers to the ok.gif file. Next, the ImageIcon instance
is passed as a parameter to JButton constructor. Next, to display the button in the container, you invoke
the add() method on the content pane instance of a container such as JApplet or a JFrame.
A JButton constructor normally accepts a string label as an argument. It is possible for a button to have
a label consisting of multiple lines. The JButton constructor can also use html text in the string label.
The html text should start with the <html> tag and terminate with the </html> tag. The html text
allows the programmer to make the label bold, italic, underline, and so on.
Code Snippet 12 shows how to create a button with an html text as its label.
Code Snippet 12:

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

JButton btnRightJustify;
btnRightJustify = new JButton(“<html><b><i>Right<br>Justify</b></i>
</html”);

Most of the Swing components which accepts a label as an argument can be provided with html text.
Also the tool tip text of these components can be formatted with html text. The html text used for labels
and tool tip should be properly embedded within the <html> and </html> tags. If it is not embedded
within the html tag, the html text will not be expanded properly, and the label will display the html code
and not the label in html form.
Table 1.10 lists the methods of the JButton class.

Method

Description

Public string getText()
Public void setText(string label)

The getText() method is used to retrieve the
text of JButton.
The setText() method can be used to dynamically
change the text of a JButton.

Table 1.10: Methods of JButton
Code Snippet 13 shows how to replace the existing caption of a button.
Code Snippet 13:
// Create a button with the text “On” on it.
JButton btnOn = new JButton(“On”);
// Assign a new caption to lblName component
btnOn.setText(“Off”);

Concepts

The Code Snippet creates a button with the caption or text “On” on it. Next, a new caption “Off” is
assigned to the button btnOn using the setText() method. This is useful when you want to use the
same button as a toggle button. For example, if the caption is “On”, you execute one set of statements;
and if the caption is “Off”, you execute another set of statements.

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Note: The javax.swing.JButton extends from javax.swing.AbstractButton, and inherits

useful methods such as:

public void setPressedIcon(Icon pressedIcon)

public void setSelectedIcon(Icon selectedIcon)

public void setRolloverIcon(Icon rolloverIcon)

public void setRolloverSelectedIcon(Icon rolloverSelectedIcon)

1.4.3 JCheckBox
The JCheckBox component creates a component which can have only two states, either checked or
unchecked. By default it is unchecked.
Table 1.11 lists the constructors of the JCheckBox.

Constructor

Description

JCheckBox():

Creates a check box without any label.
JCheckBox(String label):
Creates a check box with the specified label; where
label identifies the text appearing beside the
square box.
JCheckBox(String label, boolean Creates a check box with the specified label and
state)
the state; where state is a Boolean value.
JCheckBox(ImageIcon icon)
Creates a check box with the specified image;
where icon is an image.
JCheckBox(String label, ImageIcon Creates a check box with the specified label and
icon)
the image; where label is a string and icon is an
image.
Table 1.11: JCheckBox Constructors

Concepts

Figure 1.19 displays a JCheckBox.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.19: JCheckBox
Code Snippet 14 shows how to create the JCheckBox labeled ‘Bold’.
Code Snippet 14:
import javax.swing.JCheckBox;
...
...
JCheckBox chkBold;
...
chkBold = new JCheckBox(“Bold”);

Table 1.12 lists the JCheckBox methods.

Description

Void setSelected(boolean state)

This retrieves the state of the JCheckBox. If
the check box is selected, it returns true else it
returns false.
This is used to set the state the JCheckBox. If
set to true then JCheckBox is selected.

Table 1.12: JCheckBox Methods
Code Snippet 15 shows how to add JCheckBox and set its state.
Code Snippet 15:

V 1.0 © Aptech Limited

Concepts

Method

boolean isSelected()

Session

1
Introduction to Swing

...
JCheckBox chkBold;
JCheckBox chkItalic;
btnOk = new JCheckBox(“Bold”);
btnOk1 = new JCheckBox(“Italic”);
container.add(chkBold);
container.add(chkItalic);
chkBold.setSelected(true);
ChkItalic.setSelected(true);
...

1.4.4 JRadioButton
The JRadioButton component creates a component which can have only two states, either checked or
unchecked, by default it is unchecked.
Table 1.13 lists the constructors of the JRadioButton.

Constructor

Action

JRadioButton():

Creates a radio button without any label.
JRadioButton(String label):
Creates a radio button with the specified label;
where label is a string.
JRadioButton(String label, boolean Creates a radio button with the specified label and
state):
the state; where state is a Boolean value.
JRadioButton(ImageIcon icon):
Creates a radio button with the specified image;
where icon is an image.
JRadioButton(String label, ImageIcon Creates a radio button with the specified label and
icon):
the image; where label is a string and icon is an
image.
Table 1.13: JRadioButton Constructors

Concepts

Figure 1.20 displays JRadioButton.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.20: JRadioButton
Code Snippet 16 shows how to create a JRadioButton.
Code Snippet 16:
import javax.swing.JRadioButton;
...
JRadioButton radBold;
radBold = new JRadioButton(“Bold”);
...

1.4.5 Grouping JRadioButton
The JRadioButton provides a convenient way to perform multiple selections of choices. These choices
are mutually exclusive, that means a user can select only one of all possible choices.
Since the radio buttons are mutually exclusive, they have to be grouped together; else they will behave
like a JCheckBox. Swing provides a class javax.swing.ButtonGroup which is used to group radio
buttons which fall in the same category. ButtonGroup is not a GUI component, it is not added to a
container, it has a method add() to simply add JRadioButton objects and group them together.
Code Snippet 17 shows how to add JRadioButton.

Concepts

Code Snippet 17:

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

JRadioButton radPlain, radBold;
ButtonGroup group;
radPlain = new JRadioButton(“Plain”, true);
container.add(radPlain);
radBold = new JRadioButton(“Bold”);
container.add(radBold);
group = new ButtonGroup();
group.add(radPlain);
group.add(radBold);

Figure 1.21 shows the output for Code Snippet 17.

Figure 1.21: Output for Code Snippet 17
Table 1.14 lists the methods for the JRadioButton class.

Methods

Description

boolean isSelected()

This

void setSelected(boolean state)

This method is used to state the text of the
JRadioButton. Is set to true, then the radio
button is selected.

method

JRadioButton.

retrieves

the

value

of

Table 1.14: JRadioButton Constructors

1.4.6 JTextField
Concepts

A JTextField component allows to input and edit a single line of text. Normally text is inputted by the
user; however you can also set text in a JTextField programmatically.
A JLabel and a JTextField go hand-in-hand in most data-entry forms, for the user to enter textual
information. A JTextField has the following constructors:

JTextField()

JTextField(String initialText)

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

JTextField(String initialText, int columns)

where,
initialText is the text appearing in the text field
columns is the number of columns in the text field.

Figure 1.22 displays a JTextField.

Figure 1.22: JTextField
Code Snippet 18 shows how to create a JTextField.
Code Snippet 18:
import javax.swing.JTextField;

Concepts

...
JTextField txtMessage;
...
txtMessage = new JTextField();
...

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Table 1.15 lists the important methods of the JTextField.

Method

Description

String getText()

void setText(String text)

void setEditable(boolean editable)

Returns the contents of the JTextField.
Programmatically sets the text in the JTextField.
If false then one cannot type or edit the contents
of the JTextField.

Table 1.15: JTextField Methods
Code Snippet 19 shows how to create, display, and set the text as a non-editable TextField.
Code Snippet 19:
JTextField txtMessage;
txtMessage = new JTextField();
container.add(txtMessage);
txtMessage.setText(“Enter correct password”);
txtMessage.setEditable(false);

1.4.7 JTextArea
A JTextArea component allows you to input and edit multiple lines of text. Normally text is entered by
the user; however you can also set text in a JTextArea programmatically.
Table 1.16 lists the JTextArea constructors.

Constructor

Action

public JTextArea():

public JTextArea(String text):
public JTextArea(int rows, int
columns)

Creates a textarea without any text
Creates a textarea with the specified text; where
text is a string
Creates a textarea with the specified rows and the
columns; where rows is an integer and a column is
an integer

Table 1.16: JTextArea Constructors

Concepts

Figure 1.23 displays a JTextArea.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.23: JTextArea
Code Snippet 20 shows how to create the JTextArea with four rows and 10 columns.
Code Snippet 20:
import javax.swing.JTextArea;
...
JTextArea txaInfo;
...
txaInfo = new JTextArea(4,10);
...

The methods of JTextArea which allows communication with the system clipboard are discussed in
detail. They are as follows:

copy() Method

The copy() method transfers the currently selected text from the text area to the system clipboard.
The selected text remains intact in the text area. If no selected text is available then method does
nothing.
Syntax:
public void copy()
paste() Method

The paste()method transfers the contents of the system clipboard into the text area at the
current caret position. If there is selected text in the textarea then the selected text is replaced
with the contents from the system clipboard. If the system clipboard is empty then this method
does nothing.
Syntax:
public void paste()

V 1.0 © Aptech Limited

Concepts

1

Session

Introduction to Swing

Code Snippet 21 demonstrates the use of copy() methods.
Code Snippet 21:
JTextArea jtaNotes;
String strSelectedText;
...
strSelectedText = jtaNotes.getSelectedText();
if (strSelectedText.equals(“”))
{
jtaNotes.copy();
}
strSelectedText = jtaNotes.getSelectedText();
if (strSelectedText.equals(“”)) {
jtaNotes.cut();
}
btnPaste.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtaNotes.paste();
}
}

1.4.8 JPasswordField
A JPasswordField is similar to a JTextField in appearance. When the user types, the asterisk
character (*) is echoed for every character typed.

Concepts

By default, the asterisk character is echoed; it can be programmatically changed to any other character
desired.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.24 displays a JPasswordField.

Figure 1.24: JPasswordField
Code Snippet 22 shows how to create a JPasswordField.
Code Snippet 22:
import javax.swing.JPasswordField;
...
JPasswordField pwdPass;
...
pwdPass = new JPasswordField();

1.4.9 Methods of JPasswordField
Table 1.17 lists the important methods of JPasswordField.
public string getText()
public void setText()

public void setEchoChar()

Description
Returns the contents of JPasswordField.
Programmatically sets the text in
JPasswordField.
Changes the default echo character to a specified
character.

Table 1.17: Methods of JPasswordField

V 1.0 © Aptech Limited

Concepts

Method

Session

1
Introduction to Swing

Code Snippet 23 shows how to retrieve text from JPasswordField.
Code Snippet 23:
JPasswordField pwdPass;
pwdPass = new JPasswordField();
container.add(pwdPass);
String strPassword = pwdPass.getText();

1.5 Event Handling
An application containing GUI components is an event driven application. This means the GUI components
respond to events. An event is occurred when a user interacts with the GUI component. It describes the
change in the state of object. For example, pressing a button by clicking it or typing of any key from the
keyboard raises the events.
In Swing applications, the delegation event model is used for handling events. It defines the standard way
for generating and processing events. The advantage of delegation event model is the separation of user
interfaces from the application logic processing the events.
In delegation event model, an event is generated by a source such as a button, listbox, and so on. The
generated event is handled by one or more listeners, which are objects that receive notification about
the occurrence of an event. The swing components are registered with the listeners to handle events
occurred on them.
The event handling mechanism was defined for AWT components, but later on was also used by Swing
components. The java.awt.event package defines different types of events generated by GUI
components in Swing. Some of the events which are specific to Swing are defined in javax.swing.
event package.
The components of delegation event model are as follows:

Event: It is an object describing a state change that has occurred in the source such as pressing of

a button or selection of an item in a list. An event can also be generated where there is no direct
interaction with the user such as expiry of a timer.

Event Source: It is an object generating the event. Source can generate more than one type of

Concepts

event.

Listeners: It is an object that receives notification when an event occurs. The listeners must be

registered with the source to receive the notification.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

Figure 1.25 shows the components of delegation event model.

Figure 1.25: Event Model

1.5.1 Registering the Events
An object that generates events can perform registering for its event handlers. An event handler asks
the event generator or component to simply inform it when the event occurs. This request is called a
registration. A component can remember all of the registered event handlers.
When the event occurs the component will send a message to its component who has registered event
handler on it. The event handler then carry out the task required.
The event handlers are the listeners that must be registered with the source, before receiving any event
notification. The benefit of this is that when events are raised, notifications are sent only to registered
listeners who can handle the event.

1.5.2 Event Listeners and their Methods
The java.awt.event package defines different types of events generated by GUI components in Swing.
Some of the events which are specific to Swing are defined in javax.swing.event package. Table 1.18
lists some of the events.Swing are defined in javax.swing.event package.
Table 1.18 lists some of the events.
Events
ActionEvent

Source
Listeners
B u t t o n , ActionListener
Menu, List
AdjustmentEvent Scrollbar
AdjustmentListener
Check box, ItemListener
List

void actionPerformed(ActionEven
t ae)
void adjustmentValueChanged(Adj
ustmentEvent ae)
void itemStateChanged(ItemEvent
ie)

Concepts

ItemEvent

Interface Methods

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Events
MouseEvent

Source
Mouse

WindowEvent

Window

Listeners
MouseListener

Interface Methods
void mouseClicked(MouseEvent
me)
MouseMotionListener void mouseEntered(MouseEvent
me)
void mouseExited(MouseEvent
me)
void mousePressed(MouseEvent
me)
void mouseReleased(MouseEvent
me)
void mouseDragged(MouseEvent
me)
void mouseMoved(MouseEvent
me)
void windowActivated(WindowE
WindowListener
vent we)
void windowClosed(WindowEvent
we)
void windowClosing(WindowEve
nt we)
void windowDeactivated(Windo
wEvent we)
void windowDeiconified(Window
Event we)
void windowIconified(WindowEv
ent we)
void windowOpened(WindowEvent
we)
Table 1.18: Events in Swing API

1.5.3 Event Handling for JButton
Concepts

Since JButton is a Swing component, the Event-Delegation Model is used to handle its events.
The JButton component listens using the java.awt.event.ActionListener interface. This
interface has one method named actionPerformed(). What should happen when a button is pressed
is specified in the action-code, and this code is specified in the actionPerformed() method.
The JButton has a method addActionListener(), which is used to register the listener object. There
are three ways to create the listener-object:

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

The application class can implement the ActionListener interface and provide the
implementation of actionPerformed() method.

Use an Inner-class as the event-handler.

Use an Anonymous-class as the event-handler.

Code Snippet 24 shows you how to handle the event of JButton labeled ‘Ok’ with the help of anonymous
class.
Code Snippet 24:
...
JButton btnOk;
btnOk = new JButton(“Ok”); container.add(btnOk);
...
// Anonymous Class btnOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Action Code
...
}
}
);

1.5.4 Event Handling for JCheckBox
A JCheckBox component listens using either java.awt.event.ActionListener or java.awt.
event.Item Listener interface.
The java.awt.event.ItemListener has one method:
The method itemStateChanged() contains the action code to be executed when a JCheckBox
component is selected or deselected.
A JCheckBox has the two methods for registering listener-objects namely addActionListener()and
addItemListener().
Code Snippet 25 shows how to handle the event of JCheckBox labeled “Bold”.

V 1.0 © Aptech Limited

Concepts

public void itemStateChanged(ItemEvente)

Session

1
Introduction to Swing

Code Snippet 25:
JCheckBox chkBold;
chkBold = new JCheckBox (“Bold”); container.add(chkBold);
...
...
// Anonymous Class chkBold.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
// Action Code
...
...
}
}
);

Figure 1.26 shows the output for Code Snippet 25.

Figure 1.26: Output for Code Snippet 25

1.5.5 Event Handling for JRadioButton
Concepts

A JRadioButton component listens using either java.awt.event.ActionListener or java.
awt.Event.ItemListenerinterface.
The java.awt.event.ItemListener has one method as follows:

void itemStateChanged(ItemEvent e)

The method itemStateChanged() contains the action code as to what should happen when a
JRadioButton component is selected or deselected.

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

A JRadioButton has two methods for registering listener-objects namely, addActionListener()
and addItemListener().
If a listener-object is registered with a JRadioButton component, then whenever the component’s state
changes from selected to deselect or vice versa, this method is invoked as part of the delegation.
Code Snippet 26 shows how to create a JRadioButton.
Code Snippet 26:
//Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic(KeyEvent.VK_B);
birdButton.setActionCommand(birdString);
birdButton.setSelected(true);
JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic(KeyEvent.VK_C);
catButton.setActionCommand(catString);
JRadioButton dogButton = new JRadioButton(dogString);
dogButton.setMnemonic(KeyEvent.VK_D);
dogButton.setActionCommand(dogString);
JRadioButton rabbitButton = new JRadioButton(rabbitString);
rabbitButton.setMnemonic(KeyEvent.VK_R);

Concepts

rabbitButton.setActionCommand(rabbitString);

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

JRadioButton pigButton = new JRadioButton(pigString);
pigButton.setMnemonic(KeyEvent.VK_P);
pigButton.setActionCommand(pigString);
//Group the radio buttons.
...
//Register a listener for the radio buttons.
rabbitButton.addActionListener( new ActionListener() { ...
public void actionPerformed(ActionEvent e) {
picture.setIcon(new ImageIcon(“images/” e.getActionCommand()
+ “.gif”));
}
});

Concepts

Figure 1.27 shows the output for Code Snippet 26.

Figure 1.27: Output for Code Snippet 26

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

1.5.6 Event Handling for JTextField
A JTextField listens using java.awt.event.ActionListener interface. It has the method
addActionListener() to register a listener-object, and if registered then when the user presses
the ‘Enter’ key in the JTextField the control is delegated to the method actionPerformed().
Sometimes, it is desirable to check when a JTextField gains or losses focus. The addFocusListener()
method can be used to add a listener object to handle the focus events. Java provides FocusListener
to handle focus events.
FocusListener

Table 1.19 lists the two methods for the java.awt.event.FocusListener.

Method

Description

public void focusGained(FocusEvent The focusGained() method is invoked
e)
when component gains focus.
public void FocusLost(FocusEvent The focusLost() method is invoked when
e)
component loses focus.

Table 1.19: java.awt.event.focusListener Methods
Code Snippet 27 shows how to handle focus events of the JTextField.
Code Snippet 27:
JTextField txtName;
txtName = new JTextField();
container.add(txtName);
...
txtName.addFocusListener(new FocusListener()
{
public void focusGained(FocusEvent e)
{

... }

public void focusLost(FocusEvent e)
{

...

}

Concepts

}
);

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

1.5.7 Event Handling for JTextArea
A JTextArea listens for events using java.awt.event.ActionListener interface. It has the method
addActionListener() to register a listener-object, and if registered then when the user presses the
‘Enter’ key in the JTextArea the control is delegated to the method actionPerformed().
Code Snippet 28 shows how to handle the action event of the JTextArea.
Code Snippet 28:
JTextArea txaNotes; txaNotes = new JTextField(); container.add(txaNotes);
txaNotes.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Code to handle Enter key
...
...
}
}
);

1.5.8 Event Handling for JPasswordField
A JPasswordField listens for events using java.awt.event.ActionListener interface. It
has the method addActionListener() to register a listener-object, and if registered then when
the user presses the ‘Enter’ key in the JPasswordField the control is delegated to the method
actionPerformed().
Code Snippet 29 shows how to add event handler to the JPasswordField.

Concepts

Code Snippet 29:

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

JPasswordField pwdPass;
pwdPass = new JPasswordField();
container.add(pwdPass);
pwdPass.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Code to handle Enter key
...
}
}
);

1.5.9 KeyListener
The user typing at the keyboard fires key events which are handled by KeyListener. The KeyListener
interface is capable of recognizing what keys are being pressed or released. There are three types of Key
events:

KeyPressed (Key Event) – Is fired when any key is pressed.

KeyReleased (Key Event) – Is fired when any key is released.

KeyTyped (Key Event) – Is fired when something is typed from the keyboard.

Here is how key listeners are utilized.
KeyListener is an interface that extends EventListener.
public interface KeyListener extends EventListener

addKeyListener method is used to register the class with the component. When the keyboard event
occurs (key press, released or typed), a keyboard event is generated. This will pass the KeyEvent to the

relevant method in the listener object.

Table 1.20 shows the methods of KeyListener.

V 1.0 © Aptech Limited

Concepts

The class interested in processing a keyboard event would implement this interface and the mentioned
methods or can alternately use the KeyAdapter interface that will provide ability to override methods
of interest.

Session

1
Introduction to Swing

Method

Description

void keyPressed(KeyEvent e)

Invoked when a key is pressed.
void keyReleased(KeyEvent e) Invoked when a key is released.
void getKeyTyped (KeyEvent Invoked when a key is typed.
e)

Table 1.20: Methods of KeyListener
Table 1.21 shows some key methods of KeyEvent.

Method

Description

char getKeyChar()
int getKeyCode()
public
getKeyLocation()

int

public getKeyText(int
keyCode)

public
boolean
isActionKey()

This method returns the character for the key event.
This method retrieves the Unicode value of the character
for the key event.
This method retrieves the location of the key that fired
the key event.
Returns a String describing the keyCode, such as ‘HOME’,
‘F1’ or ‘A’.
This returns true if the key firing the event was an action
key such as cut, copy, paste, and so on.
Set the keyChar value to indicate a logical character.

void setKeyChar(char
keyChar)
void
setKeyCode(int Set the keyCode value to indicate a physical key.
keyCode)

Table 1.21: Methods of KeyEvent
Code Snippet 30 demonstrates the use of keyListener.
Code Snippet 30:
public class MyPanel extends JPanel implements KeyListener {
private char c = ‘e’;
public MyPanel() {
this.setPreferredSize(new Dimension(500,500));

Concepts

addKeyListener(this);
}
public void paintComponent(Graphics g) {
super.repaint();
g.drawString(“the key that pressed is” + c, 250,250);

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

}
public void keyPressed(KeyEvent e) {
c=e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
c=e.getKeyChar();
repaint();
}
public static void main(String[] s) {
JFrame f=new JFrame();
f.getContentPane().add(new MyPanel());
f.pack();
f.setVisible(true);
}}

1.5.10 FocusListener
When a component gains or losses keyboard focus, focus events are fired. The change in focus can occur
through the mouse, keyboard, or programmatically. The FocusListener reports every focus gained
and focus lost event.
Syntax:
public interface FocusListener()

Here is how focus listeners are utilized.
FocusListener is an interface that extends EventListener.

The class interested in processing a focus event would implement this interface and the mentioned
methods or can alternately use the FocusAdapter interface that will provide ability to override methods
of interest.
The addFocusListener method is used to register the class with the component. When the focus event
occurs (focus gained or lost by a component), a focus event is generated. This will pass the FocusEvent
to the relevant method in the listener object.

V 1.0 © Aptech Limited

Concepts

public interface FocusListener extends EventListener

Session

1
Introduction to Swing

Table 1.22 shows the methods of FocusListener.

Method

Description

void focusGained(FocusEvent e) This method is invoked when a component gains
void focusLost(FocusEvent e)

keyboard focus.
This method is invoked when a component losses
keyboard focus.

Table 1.22: Methods of FocusListener
Code Snippet 31 demonstrates how to implement a FocusListener.
Code Snippet 31:
//A JButton attached to the FocusListener
JButton exButton = new JButton(“Example Button”);
exButton.setActionCommand(“Example Button”);
exButton.addFocusListener(this);
//A JCombo attached to the FocusListener
String[] items = {“London”, “Paris”, “Madrid”, “Moscow”, “Wellington”};
JComboBox exCombo = new JComboBox(items);
exCombo.addFocusListener(this);
JLabel exLabel = new JLabel(“Graphical Components:”);
//A JTextField attached to the FocusListener
JTextField exTextField = new JTextField(“A Text Field”);
exTextField.addFocusListener(this);
//A JTextArea attached to the FocusListener. It’s put in

Concepts

//a JScrollPane to be able to handle all the events created.
exTextArea = new JTextArea(“Event Feedback..”);
exTextArea.addFocusListener(this);
JScrollPane scrollText = new JScrollPane(exTextArea);

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

//Place all the components in the JFrame
...
...
...
}
//The FocusListener methods append information about
//the focus events to the JTextArea
@Override
public void focusGained(FocusEvent e) {
exTextArea.append(e.getComponent().getClass().getName() + “ has got the
focus\n”);
}
@Override
public void focusLost(FocusEvent e) {
exTextArea.append(e.getComponent().getClass().getName() + “ has lost the
focus\n”);
}
}

Figure 1.28: Output for Code Snippet 31

V 1.0 © Aptech Limited

Concepts

Figure 1.28 shows the output for Code Snippet 31.

Session

1
Introduction to Swing

1.5.11 MouseListener
To handle mouse events, the MouseListener and the MouseMotionListener interfaces are
implemented. The user interactions with components are notified by mouse events. Mouse events take
place whenever the user presses or releases a mouse or enters and leaves a component’s onscreen
area.
The addMouseListener() method can be used to add a mouse listener to the textarea or any other
components to receive mouse events. This method takes an argument of any class which implements the
MouseListener interface, or extends the MouseAdapter class. The MouseAdapter class implements
the interface.
Syntax:
public void addMouseListener(Mouse Listener e)

where,
e: is an object of any class which implements the MouseListener interface or extends the
MouseAdapter class.

Code Snippet 32 demonstrates the use of MouseListener interface.
Code Snippet 32:
JTextArea jtaNotes;
...
jtaNotes.addMouseListener(new Mouse Listener() { public void
mousePressed(MouseEvent e) {
// Add code to handle mouse button pressed
...
}
public void mouseReleased(MouseEvent e) {
// Add code to handle mouse button released
...
}

Concepts

public void mouseClicked(MouseEvent e) {
// This method is invoked as a result of
// mouse button pressed and released
...
}
public void mouseEntered(MouseEvent e) {

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

// This method is invoked when the mouse
// pointer enters into the textarea
}
public void mouseExited(MouseEvent e) {
// This method is invoked when the mouse
// pointer exits the textarea
}
});

1.6 Creating Swing Application in NetBeans IDE
NetBeans IDE is a free, open-source, cross-platform integrated development environment with
built-in support for Java Swing programming. It has many advantages when compared to coding with a
text editor. It provides quick design and development of GUI components by supporting features such
as drag and drop. The automatic code generation feature of NetBeans simplifies the GUI development
process. This allows the user to focus on the application logic rather than the underlying infrastructure.
The IDE’s GUI Builder makes it possible to build professional-looking GUIs without an intimate
understanding of layout managers. You can layout your forms by simply placing components where you
want them.

1.6.1 Setting Up the Project Using NetBeans IDE

To add a new project to the NetBeans IDE, click File menu to and select New Project to open the
New Project dialog box.

To select java in the Categories pane, click Java Application under Projects pane.

Click Next.

Enter project1 in the Project Name box to provide a name to the project. Select the location
where you want the project to be created.

In the Create Main Class box, delete default content.

Select Set as Main Project check box.

Click Finish.

V 1.0 © Aptech Limited

Concepts

To create a swing project using NetBeans IDE, perform the following steps:

Session

1
Introduction to Swing

1.6.2 Developing GUI Application in NetBeans IDE
When the IDE is loaded, the Project pane in the left pane shows the newly created project.
To add a blank form, perform the following steps:

Right-click the project name and click New → JFrame Form.

Enter Form1 in the Class Name box.

Enter formpack in the Package box.

Click Finish to create the form.

To develop the GUI application:

Add Components: Though the IDE’s GUI Builder simplifies the process of creating Java GUIs, it is

often helpful to sketch out the way you want your interface to look before beginning to lay it out.
To add a component:

1.

Select the Panel component in the Palette window, by clicking and releasing the mouse
button.

2.

By moving the cursor to the upper left corner of the GUI Builder form, locate the component
near the top left edges of the container.

3.

Align the component according to the horizontal and vertical guidelines that appear.

4.

Click in the form to place the components in this location.

Align Components: Every time you add a component to a form, the GUI Builder effectively aligns

Concepts

them, as evidenced by the alignment guidelines that appear.

1.

Press the Ctrl key and click to select the component on the left side of the form.

2.

Click the Align Right in Column button in the toolbar. You can also right-click either one and
choose Align → Right in Column from the popup menu.

3.

Repeat this for every component that needs aligning.

Finish Up: Now we need to add the buttons that will enable users to confirm the information

entered by the user.
1.

Select the Button component in the Palette Window.

2.

Move cursor over the form until guideline appears to indicate the JButton right edge is
aligned with the lower corner of the JFrame.
V 1.0 © Aptech Limited

1

Session

Introduction to Swing

3.

Click to place the button.

4.

Set display text for the button.

5.

Press Ctrl+Save to save the file.

1.6.3 Developing Application Logic
Steps to developing the GUI application logic:

Change the Default Variable Names: Change the default names of the variables to something

more meaningful as the default names are not relevant.

Register the Event Listeners: The NetBeans IDE makes event listener registration extremely

simple.

Add the code: The final step is to simply write the code into the empty method body.

1.

In the Design Area, click Action button to select it.

2.

Right-click the button and choose Events → Action → ActionPerformed. This will generate
the required event-handling code, leaving you with empty method bodies in which you add
your own functionality.

1.6.4 Compiling and Executing GUI Application

NetBeans provides Compile on Save feature, so you do not have to compile your project manually.
When you save a Java source file, the IDE automatically compiles it.

To turn off Compile on Save feature, right-click in your Project, select Properties and select
Compiling tab. Uncheck compile on save check box.

To build the whole project, Select the project node in the Projects window and choose Build
Project, to compile your whole project. The Output window allows you to view the build progress.

If the output concludes with the statement BUILD FAILED, you may need to check the code for
syntax errors. Errors are reported in the Output window as hyperlinked text. Click a hyperlink that
reports the error to navigate to the source of an error. Choose Build Project after fixing the errors.

When you build the project, class files are generated. To generate the location of the new files,
open the Files window and expand the folder for the project.

Finally, you run the program.

V 1.0 © Aptech Limited

Concepts

Next, we need to compile the program:

Session

1
Introduction to Swing

Run the Application: Running the application is simply a matter of choosing Run → Run Main

Project within the NetBeans IDE.

Note: You can also use the Build Main Project and Run Main Project commands in the main menu.

However, these commands work only work on the project that is currently designated as the ‘main’
project. You can make a project the main project by right-clicking its node in the Projects window and
choosing Set Main Project.

1.7 Common Methods of Swing Components
Most, but not all, Swing components inherit directly or indirectly from the JComponent class, which is
an indirect subclass of the old AWT Component class. Since there are a few Swing components classes
that do not inherit from JComponent, it is useful to divide the JComponent methods into two types:
those that are inherited indirectly from the old AWT Component class and those that are defined in the
JComponent class itself.
Example of Old AWT Methods are as follows:

void setBackground(Color c)

void setForeground(Color c)

void setFont(Font f)

void setEnabled(boolean b)

void setVisible(boolean b)

Concepts

Examples of JComponent Methods are as follows:

void setMinimumSize(Dimension dim)

void setPreferredSize(Dimension dim)

void setMaximumSize(Dimension dim)

void setBorder(Border b)

void setToolTipText(String txt)

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

1.7.1 setIcon ()

The setIcon() method is denied in the class javax.swing.AbstractButton. Only components
which are derived from AbstractButton class such as JButton, JCheckBox and so on inherit this
functionality.
This method takes one parameter, an object of an interface javax.swing.Icon. This method is used
to set the icon image of a component.
Swing provides the class ImageIcon as a concrete implementation of javax.swing.Icon interface.
The class javax.swing.ImageIcon is normally instantiated and sent as a parameter to setIcon()
method.
Figure 1.29 displays the use of setIcon() method.

Figure 1.29: setIcon ()

1.7.2 Using setIcon()
Java supports images of type jpeg, gif, and png. To create an instance of ImageIcon class that refers to
an image file, you use one of the following constructors:

ImageIcon (String filename)

Creates an image icon with the specified file name
ImageIcon(Image img)

Creates an image icon from an image object
Code Snippet 33 shows how to set icon of JButton “Ok” using an image file named “Ok.gif”.
Code Snippet 33:
JButton btnOk;

V 1.0 © Aptech Limited

Concepts

Session

1
Introduction to Swing

btnOk = new JButton(“Ok”); btnOk.setIcon(new ImageIcon(“Ok.gif”));

1.7.3 setMnemonic()
Mnemonics allows one character in the components label to be underlined. The component can be
either clicked with a mouse or alternately with the Alt key and the mnemonic character combination.
For example, a button with the label Connect can be made to fire an event by pressing the Alt + C
keys combination.
Following are two versions of setMnemonic() methods defined in AbstractButton class:

public void setMnemonic(char mnemonic)

This method takes a character as an argument to represent the Mnemonic. For example, character
‘C’ represents the mnemonic C.

public void setMnemonic(int mnemonic)

This method takes an integer as an argument to represent the numeric key. The class KeyEvent
has constants to represent keys. For example, KeyEvent.VK_C represents the key “C”.
Figure 1.30 displays the use of setMnemonic() method.

Concepts

Figure 1.30: setMnemonic()
Code Snippet 34 shows how to set Mnemonic of the JButton labeled “Cancel”.
Code Snippet 34:
...
btnCancel.setMnemonic(‘C’);

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

// Or
...
btnCancel.setMnemonic(KeyEvent.VK_C);
// You need to add the following code as well to ensure that the mnemonics
// are displayed when using Windows look and feel.
UIManager.put(“Button.showMnemonics”, Boolean.TRUE);

1.7.4 setToolTipText()
A tool tip is a visual textual feedback from a component when the mouse cursor hovers over a component.
It is especially useful when components have small icons but may not depict the immediate meaning of
the component. A tool tip makes it clear what the component is meant for. A tool tip can be also used on
a component to comprehend additional information for the user.
Figure 1.31 displays the use of setToolTipText() method.

\
Figure 1.31: setToolTopText()
Code Snippet 35 shows how to set the tool tip text for the JButton labeled “Save”.
btnSave.setToolTipText(“Save”);

1.7.5 setBackground()
The setBackground() method is used to set the background color of the component.

V 1.0 © Aptech Limited

Concepts

Code Snippet 35:

Session

1
Introduction to Swing

To set the color, you use the Color class. The setBackground() method accepts a color constant
defined in Color class or an instance of Color class. An instance of Color class accepts three integer
parameters – one for red, one for blue, and another one for green component of a color. The red, green,
and blue parameters can be in the range 0 to 255.
Code Snippet 36 shows how to set background color as cyan of the JButton named btnOK.
Code Snippet 36:
// Set the background color of button to cyan
btnOk.setBackground(Color. cyan);
// Set the background color button to a bluish shade
btnOk.setBackground(new Color(150,25,30));

Figure 1.32 shows the setBackground() method.

Concepts

Figure 1.32: setBackground()

1.7.6 setForeground()
The setForeground() method is used to set the foreground color of the component.
Code Snippet 37 shows how to set foreground color as red of the JButton “Ok”.
Code Snippet 37:

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

...
btnOk.setForeground(Color.red);
// Or
...
btnOk.setForeground(new Color(150,25,30));

Figure 1.33 shows the setForeground() method.

Figure 1.33: setForeground()

1.7.7 setBorder()
Swing supports decorative and non-decorative borders, which any component inherited from
JComponent can have. Normally these borders are useful for general-purpose containers such as
JPanel, JScrollPane, and so on which do not have any visible border; however you can set a border
for any component using the setBorder() method.

To set a border to a component, you use the setBorder() method and the BorderFactory class:

javax.swing.BorderFactory

The BorderFactory class implements the Border interface. The BorderFactory class has static
methods which can be used to create various borders such as bevel border, etched border, and so
on.

V 1.0 © Aptech Limited

Concepts

The borders are available in javax.swing.border package. This package contains classes to create
individual borders or compound borders by combing two different borders.

Session

1
Introduction to Swing

setBorder (Border border)

The method setBorder() takes one parameter, an object of an interface Border. The static
methods of BorderFactory class return a reference of type Border.
Figure 1.34 displays the use of setBorder() method.

Figure 1.34: setBorder()
Code Snippet 38 shows how to set the etched border of a JPanel.
Code Snippet 38:
Border border = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
pnlFonts.setBorder(border);
// Alternative way of setting border
pnlFonts.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.
RAISED));

The BorderFactory class provides means to create a compound border by combining two different
borders in to one. Two compound borders can be combined to form a third compound border.
Code Snippet 39 demonstrates the use of BorderFactory class.
Code Snippet 39:

Concepts

JPanel pnlPanel; pnlPanel = new JPanel();
Border raisedbevel, loweredbevel;
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
//Compound borders Border compoundBorder;

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

//Creates a compound border
compoundBorder = BorderFactory.createCompoundBorder(raisedbevel,
loweredbevel);
// Set the compound border to a panel
pnlPanel.setBorder(compoundBorder);

1.7.8 setEnabled()
A component which is enabled can respond to user inputs. The components which are disabled cannot
respond to user inputs. Disabled components are displayed in gray color to visually indicate that they
are not enabled. To enable a component, you use the setEnabled() method. All components which
extend from javax.swing.JComponent inherit this method.
Components such as JButton, JCheckBox, and so on when disabled using the setEnabled()methods
will not fire any event.
Figure 1.35 displays the use of setEnabled() method.

Concepts

Figure 1.35: setEnabled()

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

1.7.9 setFont()
The setFont() method is used to set the current font of the component. It accepts a java.awt.Font
object as a parameter.
Figure 1.36 displays the use of setFont() method.

Figure 1.36: setFont()
To set the font of the JButton “Ok”, the following statements:
Font f = new Font(“Times New Roman”, Font.PLAIN, 12);
btnOk.setFont(f); are used.

A Font object takes the following three parameters:
A font name such as “Courier New”, “Verdana”, and so on.

A font style such as plain, bold, or italic. Styles are available as predefined constants such as
Font.PLAIN, Font.BOLD, and Font.ITALIC.

Concepts

You can combine italic with either plain or bold in the following manner:
Font.BOLD | Font.ITALIC

A font size such as 10.

V 1.0 © Aptech Limited

1

Session

1.7.10

Introduction to Swing

setVisible()

The setVisible() method is used to make a component either visible or invisible. Normally used on
general-purpose containers such as JPanel to make all its constituent components invisible in one go.
The setVisible() method can also be used to make an individual component visible or invisible.
Figure 1.37 displays the use of setVisible() method.

Figure 1.37: setVisible()
Code Snippet 40 shows how to make the JPanel named pnlFonts invisible.
Code Snippet 40:
...
pnlFonts.setVisible(false);

When the setVisible(true) method is invoked on a top-level container such as JFrame, it puts
the frame in a state known as a realized state. Once a top-level container is in a realized state adding
components to a frame will have unpredictable results. The GUI components may fail to refresh and
update properly. After the statement setVisible(true) any statement other that adding components
are allowed.

V 1.0 © Aptech Limited

Concepts

The setVisible() method can be invoked by the top-level containers and also by the components.
For components this method simply makes the component visible or invisible. However, for a toplevel container such as JFrame, no components should be added to the content pane after the
setVisible(true) method has been invoked.

Session

1
Introduction to Swing

Code Snippet 41 shows the use of the setVisible(true) method.
Code Snippet 41:
JButton btnStart; Container contentPane; Thread serverThread;
...
// Retrieve the ContentPane contentPane = getContentPane();
// Create and add all components
...
btnStart = new JButton(“Start Server”);
contentPane.add(btnStart);
// Make the frame visible
setVisible(true);
// DO NOT ADD GUI COMPONENTS BELOW
// Start the server thread
serverThread = new Thread(this);
serverThread.start();

1.8 Concurrency in Swing
Computer users take assume that their systems can perform multiple actions at a time. Often, even a
single is expected to perform more than one thing at a time. Software that can do such things is known
as concurrent software. A well-written Swing program uses concurrency to create a user interface that
never ‘freezes’. This means that the program is always responsive to user interaction, even when it is
already doing something else.

1.8.1 Threads in Swing
A Swing program deals with following types of threads:

Concepts

Initial Thread

The initial thread is referred to as the main-thread. When a Java program is executed, the JVM starts
the main thread, which executes the static main() method of the application. This thread is
responsible for all aspect of the program’s execution including memory access, I/O operations, and
so on except the Swing related GUI.

Event-Dispatch Thread

When JVM encounters Swing related operation for the first time it starts another thread to handle

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

the Swing components.
This thread is referred to as the event-dispatch thread, which is responsible for all aspects of the
GUI components. Swing event-handling and painting related code is placed inside event-dispatch
thread. This ensures that one event handler completes execution after another and painting is
not affected by any external interruption. Swing components and models are to be created and
modified in event-dispatch thread to avoid deadlock situation.
Every GUI application has an event-dispatch thread; this thread waits for events to occur and
then dispatches those events to the appropriate event handlers. All the event listener methods
are invoked by the event-dispatch thread, so any GUI related task one performs from an event
listener are safe. GUI related task involves getting/setting values in components such as TextField,
or changing state of components such as check boxes and radio buttons.
However, if the GUI related task involves external events such as getting a database connection,
performing I/O operation, and so on then the main-thread and the event-dispatch thread can get
into a deadlock or could race for CPU time. If such a situation occurs, the Swing based application
could either crash or become non-responsive.

Worker threads

These are also known as background threads, where time-consuming background tasks are
executed.

1.8.2 SwingUtilities.invokeLater() Method
The javax.swing.SwingUtilities class provides a static utility method, invokeLater() that
allows the execution of arbitrary code from the event-dispatch thread. A Runnable object is passed as an
argument to the invokeLater() method. The run() method of this object is invoked from the eventdispatch thread. The invokeLater() method returns immediately regardless of when the run()
method is invoked.

Using the SwingUtilities.invokeLater() method ensures that the imminent clash between the
main-thread and the event-dispatch thread is averted.

1.8.3 Thread Safety in Swing Methods
Swing components are not designed to be thread-safe for reasons of efficiency. This means that the
Swing components should be manipulated by a single thread at a time. The easiest way to ensure this is
to perform all GUI manipulations from the event-dispatch thread.

V 1.0 © Aptech Limited

Concepts

The invokeLater() method do not run the Runnable object immediately. Instead, the method
encapsulates the Runnable object within a special event object and places the event on the event
queue. When all the pending GUI events have been handled, the Runnable object is extracted from the
event queue and the event dispatch thread invokes its run() method. This means that invokeLater()
method provides a useful way to defer the execution of some arbitrary non GUI related code until all
pending events have been processed.

Session

1
Introduction to Swing

1.9 Check Your Progress
1.

Which of the statements about JFC and Swing are true?
A.
B.
C.
D.
E.
(A)
(B)

2.

The Java Foundation Classes (JFC) was introduced since JDK 1.0.
The JFC include 2D graphics support.
Swing is based on a toolkit.
Swing supports a technology called ‘Pluggable Like and Feel’.
JFC is non-graphical framework.
(C)
(D)

A, B, and E
C, D, and E

A, B, and C
B, C, and D

Can you match the descriptions against the corresponding features of AWT and Swing?
Features
A.
B.
C.
D.
E.

Description

AWT
Peer components
Swing components
Lightweight components
Heavyweight components

(A) A-4, B-2, C-5, D-1, E-3
(B) A-4, B-2, C-5, D-3, E-1
3.

Concepts

Swing
Platform dependent
Abstract Window Toolkit
GUI based application
Platform independent

(C) A-2, B-4, C-5, D-1, E-3
(D) A-5, B-2, C-4, D-3, E-1

Which of these statements about MVC and Separable Model Architecture are true?
A.
B.
C.
D.
E.

MVC Architecture was first introduced in Smalltalk.
Model represents the view of the Component.
Controller reacts to user inputs from Keyboard and Mouse.
View represents the data.
Separable Architecture combines the View and Controller.

(A) A, B, and E
(B) C, D, and E
4.

1.
2.
3.
4.
5.

(C) A, B, and C
(D) A, C, and E

Which statements about container are true?
A.
B.
C.

Glass pane is hidden by default.
Layered pane can hold components in specified Z-order.
The menu bar can be added to the content pane.

V 1.0 © Aptech Limited

1

Session

6.

D.
E.

The general purpose container cannot be added to a top level container.
The object reference of a content pane is retrieved using the getContentPane()
method.

(A)
(B)

A, B, and E
B, C, and E

A.
B.
C.
D.
E.

The JPanel is a container and not a component.
The setSize() method brings JFrame into realized state.
By default, close operation of JFrame is not functional.
Applet makes Web pages more dynamic.
The stop() method of JApplet is invoked only once in life time of JApplet.

(A)
(B)

C, D, and E
A, D, and E

(A)
(B)

A, B, and C
B, C, and D

JPasswordField
can be created
JPasswordField(“Pass word”);

with

the

constructor

public

JTextField allows to input single line of text.

The method setEditable(false) allows you to edit the text.
JTextArea does not allow you to edit the text.
The text in the JTextArea can be set programmatically.
B and E
C and D

(C)
(D)

A and C
E and D

You are trying to set the icon for a JButton labeled “Ok ”. Which of the following code will help you
to achieve this?
A.
B.
C.
D.

(C)
(D)

Which of the following statements about JTextField, JTextArea, and JPasswordField are
true?

B.
C.
D.
E.

8.

A, B, C, and D
B, C, D, and E

Which of the statements about JFrame, JApplet, and JPanel are true?

A.

7.

(C)
(D)

JButton btnOk = new JButon(“Ok”, new ImageIcon(“Ok.gif”));

JButton btnOk = new JButton(new ImageIcon(“Ok.gif”), “Ok”);
JButton btnOk = new JButton(“Ok”, new ImageIcon(“Ok.gif”));
JButton btnOk = new JButon(new ImageIcon(“Ok.gif”));

You are trying to set the mnemonic and tool tip text of the JButton labeled “Cancel”. Which of
the following code will help you to achieve this?

V 1.0 © Aptech Limited

Concepts

5.

Introduction to Swing

Session

1
Introduction to Swing
A.

btnCancel. setMemmonic (‘C’);

B.

btnCancel.setToolTiptext(“Cancel operation”);
btnCancel.setMnemonic(‘O’);

C.

btnCancel.setToolTipText(“Cancel operation”);
btnCancel.setMnemonic(‘C’);

D.

btnCancel.setToolTipText(Cancel operation);
btnCancel.setMnemonic(KeyEvent.VK_O);

Concepts

btnCancel.setToolTipText(“Cancel operation”);

V 1.0 © Aptech Limited

1

Session

Introduction to Swing

1.9.1 Answers
D
A
D
A
A
A
C
D

Concepts

1.
2.
3.
4.
5.
6.
7.
8.

V 1.0 © Aptech Limited

Session

1
Introduction to Swing

Summary
JFC is a graphical framework which includes the older AWT, Swing and Java2D. Swing is framework
based on the Model-View-Controller architecture as compared to AWT which was just a toolkit.

Model-View-Controller Architecture (MVC) is an object-oriented user interface design pattern first
introduced in Smalltalk somewhere in the late 1970s.

A Container is meant to contain components. There are two types of Containers, Top-Level
Container and General-Purpose Containers.

Swing components are referred to as Lightweight components. Lightweight components render
(draw) themselves with pure Java code, and hence, do not depend upon external native language
code such as C/C++ which forms the peer equivalent.

NetBeans IDE provides a smooth environment for swing applications. They allow a better plumbing
that the user would have to code in. NetBeans does not add overhead thus making the
supplication time and work efficient.

Swing provides various methods that are common to most GUI components. Some of these
methods are setIcon(), setMnemonic(), setToolTipText(), setBackground(), setForeground(),
setBorder(), setEnabled(), setFont(), and setVisible() method.

A good swing application uses concurrency to ensure it never freezes. This is handled by Swing
Threads such as event Dispatch Threads and initial Threads.

Concepts

V 1.0 © Aptech Limited

Session 2
Basic Swing Components
Welcome to the Session, Basic Swing Components.
This session introduces various Swing lightweight components, such
as JScrollPane, JSlider, and JProgressBar. The session also describes
the advanced text components which support styles to the input text.
The session also explains how to apply icons and borders to the Swing
components. Finally, the session concludes with the explanation of dialog
boxes and their use for accepting user input and display alerts.
In this Session, you will learn to:
 Explain JScrollPane and its methods
 Explain JSlider and its methods
 Explain event handling of JSlider
 Describe JProgressBar and its methods
 Explain event handling of JProgressBar
 Describe JFormattedTextField
 Describe JEditorPane and JTextPane
 Explain ImageIcon and Border API
 Identify and explain the need of dialog boxes
 Identify and explain the different types of JOptionPane
 Explain JDialog and its methods

2

Session

Basic Swing Components

2.1 Introduction
The Swing API provides various lightweight components that are useful in visually depicting and
manipulating progress. Some of these components are as follows:

JScrollPane – Allows scrolling of a component’s view.

JSlider - Allows the user to select a value by sliding a knob at a given interval.

JProgressBar - Allows the user to follow the progress of a task.

All these components are derived from JComponent class available in javax.swing package.
Additionally, a developer can also customize their features based on the application requirements.

2.2 JScrollPane
A JScrollPane provides a scrollable view of a component. Some of the Swing components like
JTextArea, JList, JTable, and JTree require more space as they expand. These components
inherently do not support scrolling facility and require a JScrollPane. Apart from the mentioned
components, a JPanel containing several components can be a good candidate for a JScrollPane.
Figure 2.1 displays the JScrollPane.

As shown in figure 2.1, a JScrollPane provides both horizontal and vertical scrolling. The JScrollPane
as part of its view provides four corners where you can add components. These corners are fixed and do
not scroll with the scrollbars.

V 1.0 © Aptech Limited

Concepts

Figure 2.1: JScrollPane

Session

2
Basic Swing Components

Apart from these four corners, two more headers are provided namely, RowHeader and
ColumnHeader.

RowHeader – A row header is provided between the top-left corner and the bottom-left corner,

which can scroll vertically as the scrollbars start scrolling.

ColumnHeader – A column header is provided between the top-left and top-right corners, which

scroll as the scrollbars start scrolling.

Figure 2.2 shows the corners and headers of JScrollPane.

Concepts

Figure 2.2: Corners and Headers of a JScrollPane
The JScrollPane has a JViewport which manages the visible area of the client. The viewport
computes the bounds of the current visible area, based on the positions of the scrollbars. The scroll panes
client is known as the view or viewport’s view. The client of a scroll pane can be changed dynamically
by invoking the setViewportView()method. The scroll pane does not have a corresponding
getViewportView() method. If the programmer requires to retrieve the client later, then the
getViewport().getViewportView() method of the scroll pane can be invoked.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Figure 2.3 shows the viewport of JScrollPane.

Figure 2.3: Viewport of a JScrollPane
As the user scrolls the scrollbar on the scrollpane, the client area which is visible also changes. An instance
of JViewport is used by JScrollPane to manage the visible area of the client. The positioning, sizing,
and displaying of the client is taken care of by the JViewport.

Figure 2.4: Three Areas of Scroll Bar
The three distinguished areas of a scrollbar are: knob, track, and button as shown in figure 2.4. On a
vertical scrollbar as the user moves the knob, the visible area of the client moves up and down. Similarly,
on a horizontal scroll bar as the user moves the knob, the visible area of the client moves back and forth.
The knob position is proportionate to the visible area relative to the client. On clicking the arrow button,
the user scrolls by unit increment whereas clicking the track, the user scrolls by block increment.

V 1.0 © Aptech Limited

Concepts

Figure 2.4 shows the three areas of a scroll bar.

Session

2
Basic Swing Components

2.2.1 Creating JScrollPane
A JScrollPane is created by invoking its constructor and passing the component as an argument. The
JScrollPane is then added to a container like any other components.
Figure 2.5 displays the creation of a JScrollPane with JTextArea.

Figure 2.5: JScrollPane with JTextArea
Code Snippet 1 shows how to add a JTextArea component to a JScrollPane.
Code Snippet 1:
JFrame frmDisplay;
JScrollPane scpScrollPane;
JTextArea txaNotes;
...
txaNotes = new JTextArea();
frmDisplay = new JFrame(“Scrolling JTextArea with JScrollPane”);
// Provides the text area to the scroll pane
scpScrollPane = new JScrollPane(txaNotes);
// Adds the scroll pane to the frame

Concepts

frmDisplay.getContentPane().add(scpScrollPane);

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Figure 2.6 shows the output for Code Snippet 1.

Figure 2.6: Output – JTextArea with JScrollPane

2.2.2 Dynamically Changing ScrollPane
The two steps to be followed by the programmer when the client of a JScrollPane is changed
dynamically with the setViewportView() methods are as follows:

Set the preferred size of the client with setPreferredSize() method.

Invoke revalidate() method on the client.

The revalidate() method is required to be invoked so that the scroll pane can update itself and adjust
the scrollbars. When the client size changes dynamically the scrollbars adjust automatically however, the
scroll pane or viewport does not resize.
Code Snippet 2 demonstrates how to dynamically change the client’s size.
Code Snippet 2:
JPanel pnlClient;
JScrollPane scpScroller;
// Initialize the Client
pnlClient = new JPanel();
pnlClient.setSize(600,600);
...
// Construct the scroll pane with the old view
scpScroller = new JScrollPane(pnlClient);
...

V 1.0 © Aptech Limited

Concepts

// Add the components of the client

Session

2
Basic Swing Components

// Resize the client
pnlClient.setSize(600,800);
// Add more components to the client
...
pnlClient.setPreferredSize(600,800);
pnlClient.revalidate();

2.2.3 Methods of JScrollPane
Table 2.1 lists some of the commonly used methods of JScrollPane.

Method

public void
setCorner(String key,
Component corner)

Description
This method is used to set a component at the corner of a scroll
pane.
The argument Key decides the place of the corner.
The valid values of key are: JScrollPane.LOWER_
LEFT_CORNER, JScrollPane.LOWER_RIGHT_CORNER,
JScrollPane.UPPER_LEFT_CORNER, and JScrollPane.
UPPER_RIGHT_CORNER.

public void setHorizon
talScrollBarPolicy(int
policy)

The argument Corner is the component to be added at the
corner.
This method determines when the horizontal scrollbar appears in
the scroll pane.
The argument policy can have one of the following values
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_
NEEDED
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS

Example:

Concepts

JScrollPane scpScrollPane = new JScrollPane();
scpScrollPane.setHorizontalScrollBarPolicy(Scroll
PaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Method

Description

public void setVertic
alScrollBarPolicy(int
policy)

This method determines when the vertical scrollbar appears in the
JScrollPane.
The argument policy can haven one of the following values:
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS

Example:
JScrollPane scpScrollPane = new JScrollPane();
scpScrollPane.setVerticalScrollBarPolicy(ScrollPa
neConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

public void setRowHeader
View(Component view)

This is used to add a vertically long component as the row header.
The component scrolls up and down. The argument view is an
object of any Swing component.
Public void setColumnHea This is used to add a horizontally long component as the column
derView(Component view)
header. The component scrolls left and right.
Table 2.1: Methods of JScrollPane
Code Snippet 3 shows how to set a label with an icon at the corner of the JScrollPane.
Code Snippet 3:
...
public static void createFrameWithIcon() {

JFrame frame = new JFrame(“Cornering Sample”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Icon columnImage = new ImageIcon(“close-icon.png”);

Icon rowImage = new ImageIcon(“down-icon.png”);

Icon mainImage = new ImageIcon(“steve-jobs.jpg”);

Icon pageUp = new ImageIcon(“pageUp.png”);
// Adds icons to the label

JLabel columnLabel = new JLabel(columnImage);

JLabel rowLabel = new JLabel(rowImage);

JLabel coverLabel = new JLabel(mainImage);

JLabel pageUpLabel = new JLabel(pageUp);

V 1.0 © Aptech Limited

Concepts

// Creates a label with icon

2

Session

Basic Swing Components

// Creates a scroll pane

JScrollPane scrollPane = new JScrollPane(coverLabel);
// Sets the label at the upper left corner of the scroll pane
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, pageUpLabel);
// Adds the label as the column header
scrollPane.setColumnHeaderView(columnLabel);
// Adds the label as the row header
scrollPane.setRowHeaderView(rowLabel);
// Sets the attributes of the frame
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);

}
...

Concepts

Figure 2.7 shows the output for Code Snippet 3.

Figure 2.7: Output – Icons in JScrollPane

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

The events are generated when the user moves the scrollbars of a JScrollPane. The JScrollPane
inherently handles these events. You do not handle the events of the JScrollPane explicitly.

2.3 JSlider
A JSlider is a component which lets the user to select a numeric value within a bounded range, by
sliding the slider on the slider bar. This component guarantees that the value selected by the user will
always be in the specified range. Examples of slider bar usage are ‘Speaker Volume’ and ‘RGB Values for
generating Color shade’.
Advantage of using a slider bar for giving a numeric value is that you can preview graphically the effect of
specifying the value dynamically.
Figure 2.8 displays a slider bar.

Figure 2.8: Slider Bar
Note - A JSlider allows painting ticks and labels. The ticks can be major and minor. The slide orientation

can be either horizontal or vertical.

2.3.1 Constructors of JSlider
A JSlider can be created using one of the constructors as shown in table 2.2.
JSlider()

Description
Creates a horizontal slider bar with the
range 0 to 100 and an initial value of
50.

Example

/* Creates a slider
bar with the default
properties */
JSlider sdrRed = new
JSlider();

V 1.0 © Aptech Limited

Concepts

Constructor

Session

2
Basic Swing Components

Constructor

JSlider(int
orient)

Description

Example

Creates a slider bar using the specified /* Creates a slider
orientation with the range 0 to 100 and bar with the default
properties and
an initial value of 50.
vertical orientation */

The argument orientation can
have one of the following values:
JSlider(int
min, int max)

JSlider(int
min, int max,
int value)

JSlider(int
orient, int
min, int max,
int value)

JSlider sdrSlider = new
JSlider(SwingConstants.
VERTICAL);
/* Creates a slider bar
with the minimum value 10
and maximum value 50 */

SwingConstants.HORIZONTAL and
SwingConstants.VERTICAL

Creates a horizontal slider bar using
the specified minimum and maximum
values with an initial value of 50.

JSlider sdrSlider = new
JSlider(10,50);

The argument min and max are the
minimum and maximum integer values
to be set.
Creates a horizontal slider bar using
the specified minimum, maximum, and
initial value.

/* Creates a slider bar
with the minimum value
10, maximum value 50 and
initial value 0 */

JSlider sdrSlider = new
JSlider(0,255,0);
/* Creates a slider bar
Creates a slider bar with the specified
orientation and the specified minimum, with the orientation
vertical, minimumvalue
maximum, and initial values.
10, maximum value 255,and
The argument orient is
initial value 0 */

one of the following values:

JSlider sdrRed = new
JSlider(SwingConstants.
VERTICAL,0,255,0);

SwingConstants.HORIZONTAL and
SwingConstants.VERTICAL.

Table 2.2: Constructors of JSlider

2.3.2 Methods of JSlider
Some of the methods of the JSlider are as shown in table 2.3.

Concepts

Constructor

public int getValue()

Description
Returns the current
position of the slider in the
slider bar as an integer.

Example

/* Retrieve the value of the
slider in the slider bar */
int sliderValue = sdrRed.
getValue();

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Constructor

Public void
setValue(intvalue)

public void
setOrientation(int
orientation)
public void
setMajorTickSpacing(int
spacing)

public void
setMinorTickSpacing(int
spacing)

Description

Example

Sets the position of the
slider in the slider bar
programmatically. The
value set in the parameter
should be within the range
of minimum and maximum
value of the slider bar.

int sliderValue = 25;

The argument value is an
integer which specifies the
position of the slider to be
set.
Sets the orientation of the
slider bar to horizontal or
vertical.

int sliderValue = 25;

. . .
sdrRed.
setValue(slidervalue);
/* Sets the value of the
slider in the slider bar */
sdrRed.
setValue(slidervalue);
/* Sets the orientation of
the slider bar horizontal */
sdrRed.setOrientation(SwingC
onstants.HORIZONTAL);

Is used to set the major tick /* Sets the major tick
spacing to 10 for a slider
spacing.
The argument spacing is
the integer value to be set
as major tick spacing.

bar with the range 0 to 50
*/

sdrSlider.
setMajorTickSpacing(10);
Is used to set the minor tick /* Sets the minor tick
spacing to 5 for a slider
spacing.
bar with the range 0 to 50
The argument spacing is */

the integer value to be set
as minor tick spacing.

public void
setPaintTrack(boolean
set)

set to true.

sdrSlider.
setPaintTicks(true);

Determines that the track
of the slider bar should be
painted, if the argument
passed is true.

/* Paints the track of the
slider bar */

V 1.0 © Aptech Limited

sdrSlider.
setPaintTrack(true);

Concepts

public void
setPaintTicks(boolean
set)

sdrSlider.
setMinorTickSpacing(5);
/* Displays the ticks on the
This displays the ticks on
the slider bar if argument is slider bar */

Session

2
Basic Swing Components

Constructor

public void
setSnapToTicks(boolean
set)

Description

slider, If true, the slider is
snapped to the nearest
tick mark where the user
positions the slider. If false
is passed as an argument
the slider moves freely
across the slider bar.

public void
setPaintLabels(boolean
set)

Example

/* Snaps the slider to the
Snaps the slider to the
nearest tick mark wherever nearest tick mark in the
slider bar */
the user positions the
sdrSlider.setSnapToTicks();

The argument set, If set
to true, the slider snaps to
the ticks. If set to false the
slider moves freely across
the slider bar.
/* Paints the labels of
This determines if the
major tick’s labels are to be major ticks on the slider
painted. If the argument is bar */
set to true then the labels
are painted.
The argument set, If set
to true, the major tick
labels are displayed. If set
to false, the labels are not
displayed.

sdrSlider.
setPaintLabels(true);

Table 2.3: Methods of JSlider

2.3.3 Event Handling
A JSlider component listens using the javax.swing.event.ChangeListener interface. A
JSlider has the method addChangeListenert or register a listener. This method is used to register
a listener with the slider bar.

Concepts

The interface ChangeListener has a method stateChanged. Every time you move the slider, the
slider bar fires an event and the control is delegated to this method.
Your application can react to this event and take appropriate action. To retrieve the current value of the
slider, you use the getValue() method.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Code Snippet 4 shows you how to add the listener to the slider bar.
Code Snippet 4:
...
JSlider sdrSlider
JSliderDemo() {
sdrSlider = new JSlider(JSlider.HORIZONTAL, -50, 50, 0);
sdrSlider.setPaintTicks(true);
sdrSlider.setMajorTickSpacing(20);
sdrSlider.setMinorTickSpacing(10);
sdrSlider.setPaintLabels(true);
// Registers the ChangeListener
sdrSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println(“Slider: “ + sdrSlider.getValue());
}
});
// Adds the JSlider on the Frame container
getContentPane().add(sdrSlider);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
...

Concepts

Figure 2.9 shows the output for the Code Snippet 4.

Figure 2.9: Output - Event Handling on JSlider

V 1.0 © Aptech Limited

Session

2
Basic Swing Components

2.4 Introduction to Timer
A Swing Timer fires one or more ActionEvent events after a specified delay. A Timer can be configured
to fire the event repeatedly or only once. To use a Timer, you have to specify the delay in milliseconds,
and listener object of type ActionListener.

2.4.1 Use of Timer in Developing GUIs
Timers are very useful in GUI application especially where animations are used to trigger the displaying
of the next frame in the animation.
Timer can be used in a GUI application where a user is supposed to respond in a stipulated time, for
example to answer a question.

2.4.2 Timer Action
A Timer is created using the following constructor:
Timer(int delay, ActionListener listener)

Creates a Timer that notifies its listeners after every delay milliseconds
Syntax:
Timer(int delay, ActionListener listener)

where,
delay: Is an integer that represents a delay in milliseconds.
listener: Is an object of an interface ActionListener. You can create it by using an

inner class or an anonymous class.

Code Snippet 5 shows how to create a timer which will repeatedly fire an action event every five seconds
to display an alert message.
Code Snippet 5:
Timer tmrAlert;
// Creates the timer with action event to be fired after every 5 seconds

Concepts

tmrAlert = new Timer(5000, new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Action Code - Display the Alert Message
}

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

});

2.4.3 Start Timer
Having constructed the timer, you invoke the start() method of the Timer class. Once started, the
timer will fire the associated action events every specified time.
The statement, tmrAlert.start(); is used to start the timer. Similarly, you can also stop the timer by
invoking its stop()method.

2.5 JProgressBar
A progress bar typically indicates the progress of a time consuming event by displaying its percentage of
completion.
Normally progress bars are used in splash screens to display the loading status of an application. They are
also used to display the progress of a time consuming operation such as copying files from one location
to another. You will typically see a progress bar in most installation programs.

Figure 2.10: Progress Bar
Swing component JProgressBar displays the progress of any task. For example, it can display a progress
bar indicating the installation progress in percentage terms.
A progress bar can be either determinate or indeterminate. A determinate progress bar is used when a
task’s duration and amount of progress is known, otherwise an indeterminate progress bar is used. An
indeterminate progress bar animates constantly to show that work is progressing consistently.

V 1.0 © Aptech Limited

Concepts

Figure 2.10 displays the progress bar.

Session

2
Basic Swing Components

Code Snippet 6 demonstrates how to use an indeterminate type progress bar.
Code Snippet 6:
JProgressBar pgb = new JProgressBar();
/* Sets indeterminate type progress bar assign boolean value to true otherwise
false */
pgb.setIndeterminate(true);

2.5.1 Constructors of JProgressBar
A JProgressBar can be created using one of the constructors as shown in table 2.4.

Constructor

JProgressBar()

JProgressBar(int
orient)

Description
Creates a horizontal progress
bar with default properties. By
default min is zero and max is
100.
Creates a progress bar with
specifies orientation. By default,
min is 0 and max is 100.

Example

JProgressBar pgbLongTask
= new JProgressBar();

JProgressBar pgbLongTask
= new JProgressBar(JProgr
essBar.VERTICAL);

The argument orient is the
integer with one of the following
valid values:
JProgressBar.HORIZONTAL,
JProgressBar(int
min, int max)

JProgressBar.VERTICAL.

Creates a horizontal progress bar JProgressBar
by default, with the specified
pgbLongTask =
minimum and maximum values.

new JProgressBar

JProgressBar(int
orient, int min,
int max)

Creates a progress bar with the
specified orientation, minimum,
and maximum values.

(0,100);
JProgressBar pgbLongTask=
new JProgressBar(JProgres
sBar.VERTICAL,0,100);

Concepts

Table 2.4: Constructor Methods of JProgressBar

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Code Snippet 7 shows how to create a vertically oriented progress bar with 0 as minimum value, 100 as
maximum value, and add it to the frame.
Code Snippet 7:
...
JProgressBarDemo() {
// Creates a panel container
JPanel jPanel = new JPanel();
// Creates progress bar with minimum value 0and maximum value 100
JProgressBar pgbLongTask = new JProgressBar(JProgressBar.VERTICAL, 0,
100);
pgbLongTask.setValue(50);
jPanel.add(pgbLongTask);
// Adds panel to the frame
add(jPanel);
// Sets the attributes of the frame
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
...

Figure 2.11: Output – JProgressBar

2.5.2 Update the JProgressBar
Once the progress bar is created and displayed, you invoke the setValue() method of the progress
bar to update the progress. The argument sent in the method should be within the bounded range of

V 1.0 © Aptech Limited

Concepts

Figure 2.11 shows the output for Code Snippet 7.

2

Session

Basic Swing Components

the progress bar. Typically, a Timer is used to determine the amount of task completed and accordingly
update the progress bar.
Code Snippet 8 shows how to determine the amount of task completed and update the progress bar.
Code Snippet 8:
JProgressBar pgbLongTask;
JFrame frmProgress;
Timer tmrProgress;
int taskCompleted = 0;
// Creates the progress bar with the minimum value0 and maximum value 100
pgbLongTask = new JProgressBar(0, 100);
// Adds the progress bar to the frame
frmProgress.getContentPane().add(pgbLongTask);
// Creates timer with the action event to be fired after every 2 seconds
tmrProgress = new Timer(2000, new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Action Code
// Compute the percentage of task completed
taskCompleted = 50;
// Update the progress bar with the percentage of task completed
pgbLongTask.setValue(taskCompleted);
...
}

Concepts

});

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

2.5.3 Methods of JProgressBar
Some of the common methods of JProgressBar are as shown in table 2.5.
void setMinimum(int n)

Description

Is used to set the minimum value /* Sets minimum value
of the progress bar to
of the progress bar.
The argument n is the minimum
integer value to be set.

void setMaximum(int n)

void setValue(int n)

void setString(String
s)

void setStringPainted
(boolean b)

Is used to set the maximum
value of the progress bar.

Is used to set progress value of
the progress bar.

pgbLongTask.
setMinimum(10);
/* Sets maximum value
of the progress bar to
50 */
pgbLongTask.
setMaximum(50);
/* Sets the value of
the progress bar to 0
*/

Is used to set the string
representation of the numeric
value of the progress bar. This
value is followed by a percentage
sign.
scpLongTask.
Determines whether the string
representation of the numeric
value is to be displayed or not. If
the argument is set to true then
the value is displayed.

Table 2.5: Methods of JProgressBar

10 */

scpLongTask.
setValue(0);
/* Displays the message
indicating that half of
the task is completed
*/

The argument b, if set to true,
then the numeric value is
displayed. If b is set to false,
then the numeric value is not
displayed.

Example

V 1.0 © Aptech Limited

setString(“Half way
reached”);
scpLongTask.
setStringPainted(true);

Concepts

Method

Session

2
Basic Swing Components

Table 2.6 lists other methods of JProgressBar.

Method

Void setIndeterminate(boolean)
Void setOrientation(int)

Setting Boolean value to ‘True’ will make
indeterminate progress bar. Setting Boolean value to
‘False’ will make it determinate, which is default.
Sets a progress bar horizontal or
vertical by specifying JProgressBar.
HORIZONTALorJProgressBar.VERTICAL.

Int getOrientation()
String getString()

Public int getValue()

public int getMinimum()
public int getMaximum()
Protected ChangeListener
createChangeListener()
public void addChangeListener(Chan
geListener cl)
public void removeChangeListener(C
hangeListener cl)
public BoundedRangeModelgetModel()
public void setModel(BoundedRangeM
odel newModel)
Protected void
fireStateChanged()

Description

Gets a horizontal/ vertical progress bar.
Gets percentage string.
Returns current value from BoundedRangeModel.
Returns current minimum value from
BoundedRangeModel.
Returns current maximum value from
BoundedRangeModel.
Used to implement custom ChangeListener.
Adds specified ChangeListener to progress bar
Removes ChangeListener from progress bar.
Returns model used by the progress bar.
Replaces current model used by progress bar.
Fires events of type ChangeEvent to its registered
listeners. Only subclasses of JProgressBar can
invoke it.

Table 2.6: Other Methods of JProgressBar

Concepts

2.5.4 Event Handling in JProgressBar
The JProgressBar component listens using the ChangeListener interface. A JProgressBar has
the addChangeListener method to register a listener. The interface ChangeListener has a method
stateChanged(). Every time the progress value of progress bar is updated, it fires an event and the
control is delegated to this method.
Your application can react to this event and take appropriate action. To retrieve the current value of the
progress bar, you use the getValue() method.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Code Snippet 9 shows how to add a listener to the progress bar.
Code Snippet 9:
pgbLongTask.addChangeListener(new ChangeListener(){public void
stateChanged(ChangeEvent ce) {
// Action Code
...
...
}
});

2.6 Advanced Text Components
Advanced text components are used for text manipulations. These components inherit from
JTextComponent class and provide other services for additional flexibility (beyond the pluggable UI and
bean support).
Some of the advanced components are as follows:

JFormattedTextField - Extends JTextField, adding support for formatting arbitrary values,

as well as retrieving a particular object once the user has edited the text.

JEditorPane - Is a text component to edit various kinds of content. This component uses

implementations of the Editor Kit to accomplish its behavior.

JTextPane - Is a component that can be marked up with attributes that are represented

graphically.

2.6.1 JFormattedTextField
In case you use a JTextField component in a GUI application, then you are responsible to check the
value that is typed in the TextField for proper format. JFormattedTextField makes it convenient to
do the validation of an input field without writing any code to check the value entered in it.

V 1.0 © Aptech Limited

Concepts

The JFormattedTextField is similar to a JTextField in appearance. It accepts characters based on
the formatter used. Different formatters are available like numeric, date, and currency.

Session

2
Basic Swing Components

Figure 2.12 displays the JFormattedTextField.

Figure 2.12: JFormattedTextField

2.6.2 Using JFormattedTextField with Numeric Formatter
To use a JFormattedTextField with a numeric formatter, you will follow these steps:

Declare an object of NumberFormat class.

Declare an object of JFormattedTextField class.

Use the static method NumberFormat.getNumberInstance()to create an instance of
NumberFormat.

Create an instance of JFormattedTextField and pass the instance of NumberFormat as an
argument to it.

Add the instance of JFormattedTextField to the container.

Code Snippet 10 shows you how to create the JFormattedTextField with numeric formatter and add
it to the frame.
Code Snippet 10:
NumberFormat numberFormat;JFormattedTextField txfNumber;JFrame frmDetails;

Concepts

// Instantiate a number format object
numberFormat = NumberFormat.getNumberInstance();
// Creates the formatted text field with numeric formatter
txfNumber = new JFormattedTextField(numberFormat);
// Adds the formatted text field to the frame
frmDetails.getContentPane().add(txfNumber);

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

2.6.3 Using JFormattedTextField with Date Formatter
To use a JFormattedTextField with a date formatter, you will follow these steps:

Declare an object of DateFormat class.

Declare an object of JFormattedTextField class.

Use the static method DateFormat.getDateInstance() to create an instance of DateFormat
class.

Create an instance of JFormattedTextField and pass the instance of DateFormat as an
argument to it.

Add the instance of JFormattedTextField to the container.

Code Snippet 11 shows how to create the JFormattedTextField with date formatter.
Code Snippet 11:
DateFormat dateFormat;
JFormattedTextField txfDate;
JFrame frmDetails;
...
// Instantiates a dateFormat object
dateFormat = DateFormat.getDateInstance();
// Creates the formatted text field with date formatter
txfDate = new JFormattedTextField(dateFormat);
// Adds the formatted text field to the frame

2.6.4 Using JFormattedTextField with Customized Formatter
To create a formatted text field with a customized format, you use the MaskFormatter class. The
MaskFormatter creates a formatter that specifies exactly which characters are legal in each position of
the formatted text field.

V 1.0 © Aptech Limited

Concepts

frmDetails.getContentPane().add(txfDate);

2

Session

Basic Swing Components

Table 2.7 lists the mask characters.
#

Mask Character


U
L
A
?
*
H

Description
Any valid number.
Escape character for escape sequence
Any character, converted to uppercase.
Any character, converted to lowercase.
Any character or number.
Any single character.
One or more characters.
Any hex character(0-9, a-f, or A-F).

Table 2.7: Mask Characters
Code Snippet 12 depicts how to create a formatted TextField to accept a nine digit number.
Code Snippet 12:
JFormattedTextField txfAmount;MaskFormatter formatter;
try
{
formatter = new MaskFormatter(“###,###,###”);
}
catch (ParseException ex)
{
System.err.println(“Exception: “+ ex.getMessage());
System.exit(0);
}
txfAmount = new JFormattedTextField(formatter);

2.6.5 JEditorPane
Concepts

A JEditorPane is a text component which can display and edit text of type plain, HTML, and RTF. The
text can be of various styles intermixed throughout the editor pane.
The JEditorPane can be created using one of the constructors as shown in table 2.8.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Constructor

JEditorPane()

Description
Creates a JEditorPane with no
text initialized.

JEditorPane(String Creates a JEditorPane with the
url) throws
contents specified by url.
IOException

JEditorPane(URL
url) throws
IOException

The argument url is the string
specifying the path of the page or
document to be displayed.
Creates a JEditorPane with the
contents from the specified url.

Example

JEditorPane epnEditor;
epnEditor = new
JEditorPane();
JEditorPane epnEditor;
epnEditor = new
JEditorPane(“http://java.
sun.com/
index.html”);
JEditorPane epnEditor;
// Creates an object of
the URL
URL url = new URL
(“http://java.sun.com/
index.html”);
// Creates a JEditorPane
// with the specified URL

JEditorPane(String Creates a JEditorPane with the
type, String text) specified Multi Purpose Internet

epnEditor = new
JEditorPane(url);
// Creates an object of
the URL

Mailing Extension (MIME) type, and URL url = new URL(
the initial text.

text/plain

“http://java.sun.com/
index.html
”);

text/rtf

/* Creates a JEditorPane
with

text: Is the initial text to be
displayed in the JEditorPane.

the specified URL and MIME
*/
epnEditor = new
JEditorPane
(url, ”text/html”);

Table 2.8: Constructor Methods of JEditorPane

V 1.0 © Aptech Limited

Concepts

The argument type is a MIME type.
It could take one of the following
values:

Session

2
Basic Swing Components

To display the JEditorPane, pass an instance of JEditorPane to the constructor of a JScrollPane,
and add the JScrollPane to the container.
Code Snippet 13 shows how to display the JEditorPane in the frame.
Code Snippet 13:
JEditorPane epnEditor;
JFrame frmEditor;
...
// Provide the editor pane to the scroll pane to facilitate scrolling
JScrollPane scpScroller = new JScrollPane(epnEditor);
// Adds the JScrollPane to the frame
frmEditor.getContentPane().add(scpScroller);

2.6.6 Methods of JEditorPane
To load text into a JEditorPane, you can either use the constructor or use one of the following two
methods as shown in table 2.9.

Method

public void
setText(String
text)

Description

Example

Is used to set the text in the
JEditorPane.

String info;

The argument text is the textual
contents to be displayed in
JEditorPane.

info = “Once upon a
time,……”;

. . .

// Sets the text in the
editor pane

Concepts

epnEditor.setText(info);

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Method

Description

public void
Is used to display the contents of
setPage(URL url)
the page referenced by the url.
throws IOException

Example

try
{

The argument url is an object of the /* Creates an URL object
class. java.net.URL specifying the
with the
path of the page to be loaded.
specified url */
URL url = new
URL(“http://java.sun.com/
index.html”);
/* Displays the contents
of the URL in the
JEditorPane */
epnEditor.setPage(url);
}
catch (IOException ex)
{
. . .
. . .
}

Table 2.9: Methods of JEditorPane
Note - The setPage()method has to be in a try-catch block as it throws IOException.

2.6.7 More about JEditorPane
JEditorPane is a text area displaying text in varied formats. As discussed HTML and RTF are the two

An HTML text is displayed in a non-editable JEditorPane. If a JEditorPane is not editable
then it supports hyperlink events. A JEditorPane can be set to be non-editable by invoking the
setEditable()method and passing Boolean value false.
To handle the hyperlink events, Swing provides the javax.swing.event.HyperlinkListener
interface. The JEditorPane has a addHyperlinkListener() method to add an object of any class
which implements the HyperlinkListener interface.

V 1.0 © Aptech Limited

Concepts

formats that are supported by the built-in version. User-defined editor kits can be developed to handle
special purpose applications. First, the setContentType() method has to be invoked to specify the
content type. Next, the setEditorKit() method will be used to specify a custom editor.

Session

2
Basic Swing Components

The HyperlinkListener interface has the method hyperlinkUpdate() which is invoked when the
user clicks link displayed in the editor pane.
Syntax:
public void hyperlinkUpdate(HyperlinkEvent e)

The following steps need to be performed in the hyperlinkUpdate() method so as to forward the link to
the appropriate page:
1.

Retrieve the event type and check if it is a ACTIVATED event
The HyperlinkEvent object, e, has the getEventType() method to retrieve the event type.
This event type is equated with HyperlinkEvent.EventType.ACTIVATED.

2.

Retrieve the source of the event
The getSource() method of the HyperlinkEvent object is used to retrieve the source of the
event. The retrieved object is typecast to JEditorPane.

3.

Check if the hyperlink event is an instance of HTMLFrameHyperlinkEvent
Use the instanceOf operator to check if the hyperlink object is an instance of
HTMLFrameHyperlinkEvent.

4.

Typecast the hyperlink event to HTMLFrameHyperlinkEvent
If the hyperlink event is an object of HTMLFrameHyperlinkEvent, typecast it to
HTMLFrameHyperlinkEvent.

5.

Retrieve the HTMLDocument object of the source of the event
The JEditorPane has a getDocument()method which retrieves the Document object, and this
document object is typecast to HTMLDocument.

6.

Invoke processHTMLFrameHyperlinkEvent() of the document object
The processHTMLFrameHyperlinkEvent() method of the document object is invoked and
the HTMLFrameHyperlinkEvent object is passed as an argument.

7.

If the hyperlink event is not an instance of HTMLFrameHyperlinkEvent
Check if the hyperlink event is an instance of HTMLFrameHyperlinkEvent. If it is not then it
means it is a URL.

Concepts

8.

Invoke the setPage()method on the source object
The hyperlink event object has a getURL()method which returns an URL object, this URL is passed
as an argument to the setPage()method of the editor pane.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Code Snippet 14 demonstrates the use of JEditorPane.
Code Snippet 14:
import java.awt.*;
import java.awt.event.*;import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
import javax.swing.text.html.HTMLDocument;
public class ReadURLFileNew extends JFrame {private JTextField urlValue;
private JEditorPane contents;
public ReadURLFileNew() {
super( “Web Browser” );
Container conObj = getContentPane();
urlValue = new JTextField( “Enter URL here” );
urlValue.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent e){getPages( e.getActionCommand() );
}
}
);
conObj.add( urlValue, BorderLayout.NORTH );contents = new
JEditorPane();contents.setEditable( false );contents.addHyperlinkListener(
new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {

if (e instanceof HTMLFrameHyperlinkEvent) {HTMLFrameHyperlinkEvent evt
= (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)contents.
getDocument();doc.processHTMLFrameHyperlinkEvent(evt);
} else {
try {

V 1.0 © Aptech Limited

Concepts

if (e.getEventType()== HyperlinkEvent.EventType.Activated)getPages(e.
getURL().toString());

Session

2
Basic Swing Components

contents.setPage(e.getURL());
} catch (Exception ex) {ex.printStackTrace();
}
}
}
}
);
conObj.add( new JScrollPane( contents ),BorderLayout.CENTER );
setSize( 400, 300 );setVisible(true);
}
private void getPages( String location ){
setCursor( Cursor.getPredeinedCursor(Cursor.WAIT_CURSOR ) );
try {
contents.setPage( location );
urlValue.setText( location );
}
catch ( IOException io ){JOptionPane.showMessageDialog( this,
“Error retrieving data from the specified URL site”,
“Check URL”, JOptionPane.ERROR_MESSAGE);
}
setCursor( Cursor.getPredeinedCursor(
Cursor.DEFAULT_CURSOR ) );
}
public static void main( String args[] ){ReadURLFileNew urlObj = new

Concepts

ReadURLFileNew();
urlObj.addWindowListener(new WindowAdapter() {
public void windowClosing( WindowEvente)

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

{
System.exit( 0 );
}
}
);
}
}

Figure 2.13 shows the output for Code Snippet 14.

Figure 2.13: Output for Code Snippet 14

2.6.8 JTextPane
A JTextPane is a text component which supports styled text. It is similar to a JTextArea in appearance.
A JTextArea can support only plain text, which can be of any font. The same font is applied throughout
the text of a text area.
A JTextPane can have plain-text, HTML, RTF (Rich Text Format) and even embedded components like
buttons and icons. The text can be of various styles intermixed throughout the TextPane.

Constructor

JTextPane()

Description
Creates a JTextPane with the
document set to null.

V 1.0 © Aptech Limited

Example

JTextPane txpText;
txpText = new
JTextPane();

Concepts

Table 2.10 shows constructors of JTextPane.

Session

2
Basic Swing Components

Constructor

JTextPane(StyledDocument
doc)

Description

Example

JTextPane txpText;

Creates a JTextPane with a
specified document.

StyledDocument doc = new
DefaultStyledDocument();

The argument doc is an object
of the class StyledDocument.

. . .
txpText = new
JTextPane(doc);

Table 2.10: Constructors of JTextPane

2.6.9 Loading Text into JTextPane
The steps to load the text in the JTextPane are as follows:

Retrieve

the StyledDocument
getStyledDocument().

of

a

Create and initialize styles.

Add styles to the style-document.

Load textual data-To load textual data the insertString()method of styled-document is used.

JTextPane

is

retrieved

using

the

method

Code Snippet 15 shows how to load text in the JTextPane.
Code Snippet 15:
JTextPane txpPane = new JTextPane();
// Retrieve the StyledDocument
StyledDocument doc = txpPane.getStyledDocument();
// To initialize a style, first retrieve the defaultstyle
Styledef=StyleContext.getDefaultStyleContext().getStyle(StyleContext.
DEFAULT_STYLE);

Concepts

// Then add a ‘regular’ style with the font ‘SansSerif’
Style regular = doc.addStyle(“regular”, def);StyleConstants.
setFontFamily(def, “SansSerif”);
// Insert text into the JTextPane by using its styled document
doc.insertString(doc.getLength(),“Thisisregulartext”,
doc.getStyle(“regular”));

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Figure 2.14 shows the output for Code Snippet 15.

Figure 2.14: Output for Code Snippet 15
Note - The styles can be regular, italic, small, and can also include components like JButton.

2.6.10 Displaying JTextPane
To display the JTextPane, pass an instance of JTextPane to the constructor of a JScrollPane. Then
add the JScrollPane to the container.
To disable editing of a JTextPane, use the setEditable()method with setting ‘False’ as an
argument.
Code Snippet 16 shows how to display the JTextPane and disable editing.
Code Snippet 16:
JFrame frmEditor;JTextPane txpPane;

// Provide the text pane to the scroll pane to facilitate scrolling
JScrollPane scpScroller = new JScrollPane(txpPane);
// Adds the JScrollPane to the frame
frmEditor.getContentPane().add(scpScroller);
txpPane.setEditable(false);

2.7 Applying Icons and Borders
The Swing components, such as labels and buttons can be associated with icons and borders. Icon is a
pictures or image that can be applied to a component. Image can be of different formats, such as GIF,

V 1.0 © Aptech Limited

Concepts

//Disables the editing of the JTextPane

Session

2
Basic Swing Components

JPEG, or PNG. Similarly, borders are used to apply fancy edges to the Swing components.

2.7.1 ImageIcon API
The Swing API provides a utility class named ImageIcon which allows you to specify an image for the
components. The image to be inserted
as icon and then associated with the component. Thus, to apply an icon from existing images to a Swing
component, you need to create an object of type ImageIcon class.
The easiest way to associate an image with a component is using the constructor of ImageIcon class.
The common constructor methods used for ImageIcon class are as shown in table 2.11.
ImageIcon()

Constructor

ImageIcon(Byte[] image data)
ImageIcon(Image image)
ImageIcon(Image image, String
description)
ImageIcon(string filename)
ImageIcon(URL location)

Description
Creates an image.
Creates an icon from an array of bytes
read from a JPEG or GIF.
Creates an image icon from an image
object.
Creates an image icon with the image
and a description.
Creates an image icon from a specified
file.
Creates an Image icon from the specified
URL.

Table 2.11: Constructor Methods of ImageIcon
Code Snippet 17 shows how to apply an image to the label component using ImageIcon methods.
Code Snippet 17:
ImageIcon i = createImageIcon(“pic.gif”, “this is my image”);
Label a = new JLabel(“Image and Text”, i, JLabel.CENTER);
...
Label2 = new JLabel(i)

Concepts

Code Snippet 18 shows how to create an image icon from the specified resource, such as a URL.
Code Snippet 18:

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

java.net.URL imgURL = myFile.class.getResource(“mypic.gif”);
...
if (imgURL != null) {
ImageIcon i = new ImageIcon(imgURL);

2.7.2 Loading Images in Applet
The end user’s browser may not support the JavaScript interpreter. In such cases the Java applet can be
deployed by manually coding the <applet> HTML tag. The JApplet supports the swing graphic library.
An applet loads image data from the same system that serves up the applet. The JApplet can load
images that are in the GIF or JPG format. The images can be loaded using the init() method.
Syntax:
public void init();

Code Snippet 19 shows how to load and display an image in JApplet.

Concepts

Code Snippet 19:

V 1.0 © Aptech Limited

Session

2
Basic Swing Components

import java.applet.Applet;
import java.awt.*;
public class animal extends Applet
{
private Image lion;
public void init()
{
lion = null;
}
public void loadImage()
{
try
{ lion = getImage(getDocumentBase(), “image1.gif”);
} catch(Exception e) { }
}
public void paint(Graphics g)
{
if (img == null)
loadImage();
g.drawImage(img, 0, 0, this);
}
}

2.7.3 Borders

Concepts

The Swing component can be applied with the borders. Borders are objects that draw the edges of
components. They can also be used to create titles or spaces around components when necessary. To
create a border around a component the setBorder() method of BorderFactory class is used.

2.7.4 Border API
The Border API can be used to apply the borders to the components. There are two ways to create the
border that are as follows:

Create a new border using the BorderFactory class
V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Using setter or getter method to apply borders

2.7.5 Creating a Border Using BorderFactory
The BorderFactory is a class that returns references for the Border objects. The BorderFactory
class is used to create borders for components. The BorderFactory class has static methods defines in
it to create predefined borders.
If the BorderFactory does not allow adequate control over the design of borders, then you can use
define to create your own borders using Border API.
Some of the methods to create borders using the BorderFactory class are as shown in table 2.12.

Method

Description

void setBorder(Border)

BordercreateLineBorder(colo
r)
createLineBorder(color, int)
BordercreateEtchedBorder()
BordercreateemptyBorder()

BordercreateemptyBorder(int,
int, int, int)
public static TitledBorder
createTitledBorder(String
title)

Sets the border of the Swing component.
Creates a line border and specifies the color of the line.
Creates a line border with specified color and width.
Creates an etched border.
Creates an invisible border.
Creates an invisible border. The arguments specify the
number of pixels that the border occupies at the four
corners.
Creates a new titled border with the specified title, the
default border type, the default text position, the default
justification, and the default font and text color.

Table 2.12: Methods of Border
Code Snippet 20 shows how to create and set simple borders using the BorderFactory class.
Code Snippet 20:
// Sets simple borders
blkln = BorderFactory.createLineBorder(Color.black);
retched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
emp = BorderFactory.createEmptyBorder();
jCompa.setBorder(blkln);
jCompb.setBorder(retched);
jcompc.setBorder(lowbev);
jCompd.setBorder(emp);

V 1.0 © Aptech Limited

Concepts

lowbev = BorderFactory.createLoweredBevelBorder();

Session

2
Basic Swing Components

2.8 Dialog Boxes
A Swing based application is created with JFrame as the top-level container. This container is physically
constrained with the maximum size offered by the screen on which it is displayed.
Complex and large applications cannot display all its GUI components on a single frame. Several
intermediate frames are required to popup based on different events in the application. This way the
overall GUI requirements can be divided based on events in the program. These popup frames are called
Dialog boxes.
The parent of a dialog box is typically the JFrame. Dialog boxes are of two types:

Modal – Modal dialog box block their parent when they popup. You have to finish the work and
close the dialog box to return back to the parent.

Non-Modal- Non-modal dialog box do not block their parent. If you click their parent, the dialog
box disappears.

Note - The javax.swing package provides a class JDialog and another class JOptionPane with

several static methods to conveniently create dialog boxes.

2.8.1 JOptionPane
The Swing component JOptionPane is presentation of option panes. An option pane is a type of dialog
box that allows the user to enter options, and depending on options selected a program can be executed
further. This component can be typically used to display feedback message or confirmation or to input
information from users.
JOptionPane is the subclass of JComponent class.

Concepts

The different types of messages supported by JOptionPane are:

ERROR_MESSAGE - Used for error message

IINFORMATION_MESSAGE - Used for information message

WARNING_MESSAGE - Used for warning message

QUESTION_MESSAGE - Used for questions

PLAIN_MESSAGE - No icon is used

The error message determines the type of icon that will be displayed on the dialog box.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Customizing Button Text
A programmer can use the JOptionPane with standard button text or with different text to create
a dialog box. The type of option pane used determines the number of button that can be used.
For example, YES_NO_OPTION dialogs have two buttons whereas YES_NO_CANCEL_OPTION dialog
has three buttons.

Code Snippet 21 demonstrates how to customize the text appearing as label of the button.
Code Snippet 21:
Object[] buttonLabel = {“Yes, please!”, “No, sorry!”};
int num = JOptionPane.showOptionDialog(frame, “Would you like Java and
Oracle?”,“A Good Question…!”,JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_
MESSAGE,null,buttonLabel,
//the titles of buttons
options[0]);

The showOptionDialog(), showMessageDialog(), and the showConirmDialog()methods
returns an integer value depending on the user’s selection. The integer variable will store the following
values: YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION and CLOSED_OPTION. Even if the text
of the button is changed, the return value is always one of the pre-defined integers.

Preventing Automatic Dialog Box Closure
The dialog box closes automatically when a button is selected from JOptionPane. To prevent this
action, the programmer has to implement own property change listener so that when the user
clicks a button, the dialog box does not close automatically.
The setDefaultCloseOperation() method of JDialog class can be used to implement a
window listener that handles the window close attempt.

Code Snippet 22 demonstrates how to implement the window listener in the method.
Code Snippet 22:
final JOptionPane displayPane = new JOptionPane(
“The only way to close this dialogis by\n”
+ “Do you understand?”,JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_
OPTION);

V 1.0 © Aptech Limited

Concepts

+ “pressing one of the following buttons.\n”

Session

2
Basic Swing Components

final JDialog dialogBox = new JDialog(frame, “Click any button”,true);
dialogBox.setContentPane(optionPane);
dialogBox.setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE);
dialogBox.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setLabel(“Prevented user attempt to close window.”);
}
});
displayPane.addPropertyChangeLis
addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (dialogBox.isVisible() && (e.getSource() == displayPane)
&& (propertyName.equals(JOptionPane.VALUE_PROPERTY))) {
//perform checking before closing the windowdialogBox
setVisible(false);
}
}
});

Concepts

Figure 2.15 shows the output for Code Snippet 22.

Figure 2.15: Output for Code Snippet 22

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

2.8.2 Creating a Dialog Box Using JOptionPane
JOptionPane provides a convenient means to display a standard dialog box for user inputs and alert

messages.

The different types of JOptionPane are as follows:

Message Dialog

This dialog box is used to alert the user with some message. The JOptionPane has the static method
showMessageDialog()to display this dialog.
Syntax:
public static void showMessageDialog(Component parentComponent, Object
message, String title, int messageType, Icon icon)

Where,
parentComponent- Is the parent of this dialog and it can be null, message is the message
to be displayed, and title is the title of this dialog.
messageType - Is the type of message to be displayed that includes: ERROR_MESSAGE,
INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE,
or PLAIN_
MESSAGE.
Icon – An icon to display in the dialog box, which identifies the kind of message that is being

displayed.

The following statement, JOptionPane.showMessageDialog(null, “Your License
has expired.”, “Security

creates a message dialog box.

warning”, JOptionPane.WARNING_MESSAGE);

Confirm Dialog

You use this dialog box to ask the user a confirming question with a ‘Yes’, ‘No’ or ‘Cancel’ button. You
use this dialog box to get a confirmation from the user. The JOptionPane has the static method
showConirmDialog()to show this dialog.
Syntax:
int

showConirmDialog(Component

parentComponent,

Object

Where,
parentComponent- The parent of this dialog and it can be null.
message- The message to be displayed.

Consider the following declaration:
Int n=JOptionPane.showConirmDialog(null, “Wouldyouliketocontinue?”,

V 1.0 © Aptech Limited

Concepts

public static
message)

Session

2
Basic Swing Components
“Confirmation”, JOptionPane.YES_NO_OPTION);

This displays the for confirmation dialog box to continue.

Input Dialog

This dialog is used to present the user with a drop-down having multiple choices to select from or
a TextField to type a value. The JOptionPane has the static method showInputDialog() to
show this dialog.
Syntax:
public static Object showInputDialog
(Component
parentComponent,
messageType,

Object

message,

String

title,

int

Icon icon, Object[] selectionValues, Object initialSelectionValue)

Where,
vparentComponent- Is the parent of this dialog; it can be null.
Message- Is the message to be displayed.
Title- Is the title of this dialog.
messageType- Is the type of message to be displayed that includes:
ERROR_MESSAGE, INFORMATION_MESSAGE,
or PLAIN_MESSAGE

WARNING_MESSAGE,

QUESTION_MESSAGE,

Icon is an icon to display in the dialog that identifies the kind of message that is being displayed.
selectionValues is an array of Object class containing all the possible values that can be selected.

If null is used, the dialog box provides a TextField.

initialSelectionValue is the value used to initialize the input field.
Consider the following statement:
Object[]
platform
=
{“Windows”,
(String)JOptionPane.showInputDialog(

“Unix”,

“Linux”};String

s=

Concepts

frame, “Which Platform do you like”, “CustomizedDialog”, JOptionPane.
PLAIN_MESSAGE, icon, platform, “Windows”);

This displays the input dialog for choosing the operating platform between Windows, UNIX, and
Linux.

Option Dialog

This dialog allows you to change the text that appears on the buttons of standard dialogs. The
JOptionPane has the static method showOptionDialog() to show this dialog.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Syntax:
public static int showOptionDialog
(Component parentComponent, Object message, String title, int optionType,
int messageType, Icon icon, Object[] options, Object initialValue)

Where,
parentComponent: Is the parent of this dialog, can be null.
message: Is the message to be displayed.
title: Is the title of this dialog box.
optionType: Is an integer with one of the following valid values: YES_NO_OPTION,YES_
NO_CANCEL_OPTION.
messageType - The type of message to be displayed that includes:
ERROR_MESSAGE, INFORMATION_MESSAGE,
or PLAIN_MESSAGE.

WARNING_MESSAGE,

QUESTION_MESSAGE,

Icon: An icon to display in the dialog box that identifies the kind of message that is being

displayed.

Options: An array of objects indicating the possible choices the user can make.
initialValue: The object that represents the default selection for the dialog.

Consider the following statement:
Object[] options = {“Connect”, “Disconnect”, “Quit”};
int n = JOptionPane.showOptionDialog(null, ”What would you like to do?”,
“Connection Message”, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

This displays the option dialog box to connect, disconnect, or quit.

Concepts

Figure 2.16 shows the types of JOptionPane dialog box.

V 1.0 © Aptech Limited

Session

2
Basic Swing Components

Figure 2.16: Input and Option Dialog Box

Concepts

Figure 2.17 shows types of JOptionPane dialog box.

Figure 2.17: Message and Confirm Dialog Box

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

2.8.3 JDialog
A JDialog is a top-level container to create custom dialog boxes. The appearance is almost similar to a
frame except that it does not have a minimize button. The process of creating, displaying, and closing of
a JDialog is almost identical to a JFrame.
To create a customized dialog box, the JDialog class is normally sub-classed. The JDialog is created
using one of the constructors as shown in table 2.13.

Constructor

Description

JDialog(Frameparent,S Creates an on-modal dialog box with the title specified.
tringtitle)
Where, parent is the container owning the dialog and title is

the name of the dialog box.
Syntax:

JDialog(Frame parent, String title)

where,
parent: Is the top-level container which owns this dialog.
JDialog(Frameparent,
Stringtitle,booleanm
odal)

title: Is the title to be given to the dialog box.

Creates a modal dialog box with the title specified if modal is
true.
Syntax:
JDialog(Frame parent, String title, boolean
modal)

where,
parent: Is the top-level container which owns this dialog.
title: Is the title to be given to the dialog box.
modal: If true the dialog box is modal.

Table 2.13: Constructors of JDialog

Concepts

Figure 2.18 shows a customized JDialogBox.

V 1.0 © Aptech Limited

Session

2
Basic Swing Components

Figure 2.18: Custom JDialogBox
Code Snippet 23 shows how to create a search dialog.
Code Snippet 23:
public class SearchDialog extends JDialog
{
// Instance data declaration
public SearchDialog(Frame parent, String title, boolean

modal)

{
super(parent, title, modal);
// Add the GUI components
...
// Handle events
...
}}

Concepts

2.8.4 Adding Components to JDialog
Components are added to the content-pane of a JDialog. By default, a JDialog box is governed by a
BorderLayout manager. To display the dialog box, you invoke the setVisible() method. After this
method invocation, you should not add any components to the dialog box.
To close the dialog box, you can invoke the setDefaultCloseOperation() method with the parameter
JDialog.DISPOSE_ON_CLOSE.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Code Snippet 24 shows how to add the button to the JDialog and close the JDialog.
Code Snippet 24:
public class SearchDialog extends JDialog
{
JButton btnSearch;public SearchDialog()
{
btnSearch = new JButton(“Search”);getContentPane.add(btnSearch);
// Closes the dialog boxsetDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// Handle events
...
}}

Figure 2.19 shows the output for Code Snippet 24.

Concepts

Figure 2.19: Output for Code Snippet 24

V 1.0 © Aptech Limited

Session

2
Basic Swing Components

2.9 Check Your Progress
1.

You are trying to add a JTextArea component to a JScrollPane. Which one of the following
codes will help you to achieve this?
A.

JScrollpane scpScrollPane;JTextArea txtNotes;txtNotes
JTextArea(); scpScrollPane = new JScrollpane(txaNotes);

=

new

B.

JScrollPane scpScrollPane;JTextArea txtNotes;txtNotes =
JTextArea(); scpScrollPane = new JScrollPane(JTextArea);

new

C.

JScrollPane scpScrollPane;JTextArea txtNotes;txtNotes
JTextArea(); scpScrollPane = new JScrollPane(txaNotes);

new

D.

JScrollPane scpScrollPane;JTextArea txtNotes;

=

txtNotes = new JTextArea(scpScrollPane);
scpScrollPane = new JScrollPane();

2.

You are trying to add the listener to the slider bar. Which one of the following codes will help you to
achieve this?
A.

JSlider sdrRed;
...
sdrRed.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
// Action code
...
...
}

Concepts

});

V 1.0 © Aptech Limited

2

Session
B.

Basic Swing Components

JSlider sdrRed;
...
sdrRed.addChangelistener(new Changelistener()
{
public void stateChanged(ChangeEvent ce)
{
// Action code
...
...
}

C.

});
JSlider sdrRed;
...
sdrRed.addChangeListener(new ChangeListener()
{
public void statechanged(ChangeEvent ce)
{
// Action code
...
...
}

Concepts

});

V 1.0 © Aptech Limited

Session

2
Basic Swing Components
D.

JSlider sdrRed;
...
sdrRed.addChangeListener(new ChangeListener()
{
public void stateChanged(Changeevent ce)
{
// Action code
...
...
}
});

3.

You are trying to create the JFormattedTextField using number format. Which one of the
following codes will help you to achieve this?
A. NumberFormat numberFormat;JFormattedTextField txfNumber;
numberFormat = NumberFormat.getNumberInstance();

B.

txfNumber = new JFormattedTextField(numberFormat);
NumberFormat numberFormat;JFormattedTextField txfNumber;
numberFormat = NumberFormat.getNumberInstance(numberFormat);

C.

txfNumber = new JFormattedTextField();
NumberFormat numberFormat;JFormattedTextField txfNumber;
numberFormat = numberFormat.getNumberInstance();

D.

txfNumber = new JFormattedTextField(numberFormat);
NumberFormat numberFormat;JFormattedTextField txfNumber;
txfNumber = NumberFormat.getNumberInstance();

Concepts

txfNumber = new JFormattedTextField();

V 1.0 © Aptech Limited

2

Session
4.

Basic Swing Components

You are trying to display the JTextPane and disable editing. Which of the following code will help
you to achieve this?
A. JFrame frmDisplay;JScrollPane scpScroller;
...
JTextPane txpPane;
scpScroller
=
new
JScrollPane(txpPane);frmDisplay.
getContentPane().add(scpScroller);

B.

txpPane.setEditable(true);
JFrame frmDisplay;JScrollPane scpScroller;
...
JTextPane txpPane;
scpScroller
=
new
JScrollPane(txpPane);frmDisplay.
getContentPane().add(scpScroller);

C.

txpPane.setEditable(false);
JFrame frmDisplay;JScrollPane scpScroller;
...
JTextPane txpPane;

D.

scpScroller
=
new
JScrollPane(JTextPane);txpPane.
add(scpScroller);txpPane.setEditable(false);
JFrame frmDisplay;JScrollPane scpScroller;
...
JTextPane txpPane;
scpScroller
=
new
JScrollPane(txpPane);frmDisplay.
getContentPane().add(scpScroller);txpPane.setEditable(false);

5.

You are trying to display confirm dialog box with the message ‘Would you like to continue?’
Which of the following code will help you to achieve this?

B.

continue?”,”Confirmation”,JOptionPane.YESNO_OPTION);
int n=JOptionPane.showconfirmDialog(null,”Would you like to

C.

continue?”,”Confirmation”,JOptionPane.YES_NO_OPTION);
int n=JOptionPane.showConfirmDialog(null,”Would you like to

D.

continue?”,”Confirmation”,JOptionPane.YES_NO_OPTION);
int n=JOptionPane.showConfirmDialog(null,”Would you like to
continue?”,”Confirmation”,JOptionPane.YES_NO_OPTION);

V 1.0 © Aptech Limited

Concepts

A. int n=JOptionPane.showConfirmDialog(null,”Would you like to

Session
6.

2
Basic Swing Components

You are trying to add a button to the JDialog subclass and close the JDialog. Which of the
following code will help you to achieve this?
A. public class SearchDialog extends JDialog
{
JButton btnSearch; public SearchDialog()
{
btnSearch = new JButton(“Search”);getContentPane.add(btnSearch)
;setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// Handle events
...
...
}

B.

}
public class SearchDialog extends JDialog
{
JButton btnSearch; public SearchDialog()
{
btnSearch = new JButton(“Search”);getContentPane.add(JDialog);s
etDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// Handle events
...
...
}

Concepts

}

V 1.0 © Aptech Limited

2

Session
C.

Basic Swing Components

public class SearchDialog extends JDialog
{
JButton btnSearch; public SearchDialog()
{
btnSearch = new JButton(“Search”);getContentPane.add(btnSearch)
;setDefaultCloseOperation(JDialog.DISPOSE_ONCLOSE);
// Handle events
...
...
}

D.

}
public class SearchDialog extends JDialog
{
JButton btnSearch; public SearchDialog()
{
btnSearch = new JButton(“Search”);getContentPane.add(btnSearch)
;setDefaultCloseOperation(JButton.DISPOSE_ON_CLOSE);
// Handle events
...
...
}

Concepts

}

V 1.0 © Aptech Limited

Session

2
Basic Swing Components

2.9.1 Answers
C
A
A
D
D
A

Concepts

1.
2.
3.
4.
5.
6.

V 1.0 © Aptech Limited

2

Session

Basic Swing Components

Summary
A JScrollPane provides a scrollable view of a component.

A JSlider is a component, which lets the user to select a numeric value within a bounded range, by
sliding a slider on the component.

JProgressBar indicates the progress of a time consuming event by displaying its percentage of
completion.

A JFormattedTextField allows only legal characters to be input in a proper format.

A JEditorPane is a text component which can display and edit text of type plain, HTML and RTF. A
JTextPane is a text component which supports styled text.

The ImageIcon class implements the Icon interface and allows applying images to the
components.

JOptionPane provides a convenient means to display a standard dialog box for user inputs and
alert messages.

Concepts

V 1.0 © Aptech Limited

Session 3
Layout Managers
Welcome to the Session, Layout Managers.
This session introduces the concept of layout manager that are used by
the containers to fix the size and position of the components. The session
explains the different types of layout managers supported by Swing API.
In this Session, you will learn to:
 State the need and purpose of layout manager
 Explain different types of layout manager
 Describe the FlowLayout manager
 Explain how to create and add components to FlowLayout
 Describe the BorderLayout manager
 Describe the GridLayout manager
 Describe the CardLayout manager
 Describe the GridBagLayout manager
 Explain BoxLayout and SpringLayout
 Explain GroupLayout
 Explain Dimension class

Session

3
Layout Managers

3.1. Introduction
All the Swing components are added within a top-level container object, such as Frame or Window.
These containers are responsible for providing some default arrangement for the components added
into them. All containers are associated with a content pane that contains the visible components.
Figure 3.1 displays a frame container with a content pane.

Figure 3.1: Frame Container with Content Pane
As shown in figure 3.1, the layout managers affect the content pane. The layout manager fixes the size
and position of components within a container. It also determines the layout for all the children for the
specified container. Thus, helping the developer to concentrate on the look and feel of the component,
rather than working on the details of positioning the components.

3.1.1 Overview of Layout Manager
All containers in Java whether top-level or general-purpose, are based on the concept of Layout Managers.
A Layout Manager is a Java object associated with a container which governs the placement and size of
the component.
All containers have a default Layout Manager associated with it. If required, one can set a different
manager to a container to change the way the components are added. A JFrame and a JApplet has
a BorderLayout by default.
Layout Managers simplify the task of adding components to the container. When the container is resized,
the layout manager is responsible to compute the new location and size of the component as required.

Concepts

3.1.2 Steps for Using Layer Manager
Normally, a layout manager for a container is set only, if the default manager of the container is not
desirable.
Typically, there are two steps involved in using a layout manager. First step is to invoke the setLayout()
method. The setLayout() method of the container is used to set a different layout. The setLayout()
method takes one parameter, an object of the required layout manager class. Java provides separate
class for each layout manager.
V 1.0 © Aptech Limited

3

Session

Layout Managers

The next step in using layout managers is to consider the sizing hints of the components. The sizing hints
determine the initial size. If the sizing hints are not specified, the layout manager cannot determine an
appropriate size to it the component in the container.
Table 3.1 shows the methods used to specify the sizing hints.

Method

void setPreferredSize(Di
mension preferredSize)

Description

Example

This is used to set the preferred size // Sets preferred
of a component when it is added to size of the button
labeled OK
the container.
Syntax:
void setPreferredSize(Dime
nsion preferredSize)

btnOk.
setPreferredSize(new
Dimension(20,20));

where,
preferredSize: is an object

void
setMinimumSize(Dimension
minimumSize)

of Dimension class used to
encapsulate the preferred width
and height of a component in a
single object.
This is used to set the minimum
size of a given component.
Syntax:
void
setMinimumSize(Dimension
minimumSize)

// Sets the minimum
size of the button
labeled OK
btnOk.
setMinimumSize(new
Dimension(20,20));

where,
minimumSize: is an object

Concepts

of Dimension class used to
encapsulate the minimum width
and height of a component in a
single object.

V 1.0 © Aptech Limited

Session

3
Layout Managers

Method

void
setMaximumSize(Dimension
maximumSize)

Description
This is used to set the maximum
size of a given component.
Syntax:
void
setMaximumSize(Dimension
maximumSize)

Example

// Sets maximum
size of the button
labeled OK
btnOk.
setMaximumSize(new
Dimension(20,20));

where,
maximumSize: is an object

of Dimension class used to
encapsulate the maximum width
and height of a component in a
single object.
Table 3.1: Methods for Sizing Components
Note - The setsize() and getsize() methods of most components use the Dimension object to

specify the size.

3.1.3 Working of a Layout Manager
When a GUI based application in Java is executed, the pack() method is invoked. This method is invoked
as a result of either the programmer has explicitly invoked it in the code, or the setVisible() method
is invoked. The setVisible() method is responsible for invoking the pack() method before the
window frame is put in the realized state.
The pack() method invokes the getPreferredSize() method of the frame to determine the best
size for laying out the components.
The getPreferredSize() method is invoked recursively for all the components until the total size
of the frame is computed. To this computed size, the size required by the edge of the frame, and the
menu bar if available is added. When the final size is available the layout manager then lays out the
components.

Concepts

3.1.4 Types of Layout Manager
Java supports different types of Layout Managers, depending on the layout needs of the GUI application.
The programmer can either use the default layout manager available or set another manager.

V 1.0 © Aptech Limited

3

Session

Layout Managers

Table 3.2 lists the different layout managers.

Layout Manager

Description

FlowLayout

Arranges the components left to right.
Allows positioning of components in five locations. East,
West, North, South, and Center.
Arranges the components in terms of rows and columns.
Arranges components like a deck of cards.

BorderLayout
GridLayout
CardLayout

Table 3.2: Layout Managers
Figure 3.2 displays the layout managers.

Figure 3.2: Types of Layout Managers

The FlowLayout manager lays the components in a row from left to right in a container. If there is
no space, it continues down in a new row again from left to right. The FlowLayout manager uses the
preferred size of the components when they are laid in a container. If the container is wider than necessary
for a row of components, then the row is centered by default.
One can specify the alignment to make it justified left or right. One can also specify the horizontal and
vertical padding required around the components.

V 1.0 © Aptech Limited

Concepts

3.2 FlowLayout Manager

Session

3
Layout Managers

Figure 3.3 displays the FlowLayout manager.

Figure 3.3: FlowLayout Manager

3.2.1 Create FlowLayout Manager
The FlowLayout manager can be created using one of the constructors shown in table 3.3.

Constructor

Description

FlowLayout() This adds the components with a centered

alignment and a gap of five pixels both
horizontally and vertically.

FlowLayout
(int)

Adds components with a specified alignment.
Syntax:

layout = new
FlowLayout();
// Creates the flow
layout // manager with
left alignment
FlowLayout layout;

where,

layout = new
FlowLayout(FlowLayout.
LEFT);

values:

FlowLayout.CENTER, FlowLayout.LEFT, or
FlowLayout.RIGHT

Adds the components with specified alignment, /* Creates the low
layout manager with
horizontal gap, and vertical gap.
Syntax:
FlowLayout(int alignment, int
horizontal-gap, int vertical-gap)

where,

Concepts

FlowLayout layout;

FlowLayout (int alignment)
alignment: is one of the following valid

FlowLayout
(int, int,
int)

Example

// Creates the flow
layout manager

horizontal_gap: is an integer variable

representing horizontal gap between
components.

left alignment,
horizontal gap of 10
pixels and vertical gap
of 15 pixels */
FlowLayout layout;
layout = new
FlowLayout(FlowLayout.
LEFT,10,15);

vertical_gap: is an integer variable

representing vertical gap between components.
Table 3.3: Constructors of FlowLayout Manager
V 1.0 © Aptech Limited

3

Session

Layout Managers

3.2.2 Setting the Layout Manager
To set layout manager, you invoke the setLayout() method of the container and pass an instance of
the FlowLayout class. Next, each component is instantiated and added to the container with the add()
method of the container.
Figure 3.4 displays the use of FlowLayout manager.

Figure 3.4: FlowLayout Manager with Alignment
Code Snippet 1 shows how to set the FlowLayout manager and add JLabel and JTextField.
Code Snippet 1:
public class Login extends JFrame
{
// GUI components declaration JLabel lblName;
JTextField txtName; public Login()
{
...
// Sets the layout of the frame to the low layout
setLayout(new FlowLayout());
// Creates a label with the name
lblName = new JLabel(“Name”);
//Adds the label to the frame
getContentPane().add(lblName);
txtName = new JTextField();
// Adds the textield to the frame
getContentPane().add(txtName);
}
}

V 1.0 © Aptech Limited

Concepts

// Creates a textield.

Session

3
Layout Managers

Figure 3.5 shows the output for Code Snippet 1.

Figure 3.5: Output - Code Snippet 1

3.2.3 Benefits and Drawbacks
The advantages of using the FlowLayout Manager are as follows:

Simple to use.

Components placed in the center of the container by default.

Suitable for JApplet which runs as part of a Web Page.

The disadvantages of FlowLayout Manager are as follows:

If the container is resized or loses the original alignment, some components may go up or down
depending upon the width.

Complex alignment cannot be achieved.

Concepts

3.3 BorderLayout Manager
The BorderLayout manager allows the user to add components in the east, west, north, south, and
center of a container. By default, if the direction is not specified then the component is placed in the
center.
In addition, BorderLayout supports four relative positioning constants, BEFORE_FIRST_LINE,
AFTER_ LAST_LINE, BEFORE_LINE_BEGINS, and AFTER_LINE_ENDS.

V 1.0 © Aptech Limited

3

Session

Layout Managers

Figure 3.6 displays the BorderLayout manager.

Figure 3.6: BorderLayout Manager
The components are laid out according to their preferred sizes and the constraints of the container’s size.
For example, the components present in the north and south directions may be stretched horizontally.
The components present in the east and west direction may be stretched vertically. Similarly, the center
component may be stretched both horizontally and vertically to fill any space left in the container.
Containers such as JFrame and JDialog have the BorderLayout
manager.

manager as its default layout

Note - In a container whose component orientation is set to ComponentOrientation.LEFT_TO_ RIGHT,

the relative positioning constants map to north, south, west, and east respectively. These constants
have a higher precedence over the direction constants; hence, it is not advisable to mix them.

3.3.1 Create the Layout and Add Components
Constructor

BorderLayout()

Description
Create the border layout with no gaps
between components.

Example

// Creates the border
layout manager
BorderLayout layout;
layout = new
BorderLayout();

V 1.0 © Aptech Limited

Concepts

The BorderLayout manager can be created using one of the constructors as shown in table 3.4.

Session

3
Layout Managers

Constructor

Description

BorderLayout(int Create the border layout with the
horizontal gap,
specified horizontal and vertical gap.
int vertical
Syntax:
gap)
BorderLayout(int horizontalgap, int vertical-gap)

where,
horizontal_gap: is an integer

Example

/* Creates the border
layout manager with
horizontal gap of 10
pixels and vertical gap
of 15 pixels */
BorderLayout layout;
layout = new
BorderLayout(10,15);

variable representing the horizontal
gap between components.
vertical_gap: is an integer variable

representing the vertical gap between
components.

Table 3.4: Constructors of BorderLayout Manager

3.3.2 Adding Components to BorderLayout Manager
If a container does not have a BorderLayout manager as its default, one can invoke the setLayout()
method of the container and pass an instance of the BorderLayout class.
The components are added to the container using the following method:

Component add(Component component, int index)

This method is used to add a component in the specified direction. The directions are East, West,
North, South, and Center. By default it is Center. The component added to the container is returned.
Syntax:
Component add (Component comp, int index)

where,
comp: Is the GUI component to be added.

Concepts

index: Is the direction where the component is to be placed. Valid value includes:
BorderLayout.EAST, BorderLayout.WEST, BorderLayout.NORTH, BorderLayout.SOUTH and BorderLayout.CENTER, BorderLayout.BEFORE_FIRST_
LINE, BorderLayout. AFTER_LAST_LINE, BorderLayout.BEFORE_LINE_
BEGINS, and BorderLayout. AFTER_LINE_ENDS.

Code Snippet 2 shows how to set the layout the JPanel to Borderlayout and add components
JLabel and JTextArea to the JPanel.
V 1.0 © Aptech Limited

3

Session

Layout Managers

Code Snippet 2:
JPanel pnlPanel;
JLabel lblStatus;
JTextArea txaNotes;
pnlPanel = new JPanel();
// Changes the layout of the panel to BorderLayout
pnlPanel.setLayout(new BorderLayout());
// Creates a label with the name “Status”
lblStatus = new JLabel(“Status”);
// Adds the label Status to the panel in the north direction pnlPanel.
add(lblStatus, BorderLayout.NORTH);
// Creates a textarea
textarea txaNotes = new JTextArea();
// Adds the textarea to the panel in the center
pnlPanel.add(txaNotes, BorderLayout.CENTER);

Figure 3.7 displays the addition of components.

Figure 3.7: Output - BorderLayout

3.3.3 Benefits and Drawbacks

Allows to specify the direction where the component is to be placed

By default the component is placed in the center

The disadvantages of using BorderLayout are as follows:

V 1.0 © Aptech Limited

Concepts

The advantages of using BorderLayout manager are as follows:

Session

3
Layout Managers

Components can be added in only four to five locations in a container.

Absolute positioning of components is not possible.

3.4 GridLayout Manager
The GridLayout manager places the components in terms of rows and columns. Each cell (where the
row and column meet) is of the same size. If the container is resized, then the available space is again
distributed uniformly amongst all the cells.
GridLayout is typically used when all the components in the container are of the same size and are

arranged in terms of rows and columns like in a ‘calculator’.
Figure 3.8 displays the GridLayout manager.

Figure 3.8: GridLayout Manager

3.4.1 Adding Components Using the GridLayout Manager
The GridLayout manager can be created using any one of the constructors as shown in table 3.5.

Constructor

GridLayout(int,
int)

Description
Creates a GridLayout manager with specified
number of rows and columns. The gap
between the grid of components created is
zero.
Syntax:

Concepts

GridLayout(int rows, int columns)
where,
rows: Is an integer specifying number of rows
columns: Is an integer specifying number of
the columns.

V 1.0 © Aptech Limited

Example

/* Creates the grid
layout manager with 5
rows and 5 columns */
GridLayout layout = new
GridLayout(5,5);

3

Session

Layout Managers

Constructor

GridLayout(int,
int, int, int)

Description

Example

Syntax:

/* Create the grid
layout manager with
5 rows, 5 columns,
horizontal gap of 10
pixels and vertical gap
of 15 pixels */

GridLayout(int rows, int columns, int
horizontal_gap, int vertical_gap)

GridLayout layout = new
GridLayout(5,5,10,15);

Creates a GridLayout with specified number
of columns and rows and with specified
horizontal and vertical gaps between
components.

where,
horizontal_gap: is the horizontal spacing
between the components.
vertical_gap: is the vertical spacing between
the components.
Table 3.5: Constructors of GridLayout Manager
Figure 3.9 shows the arrangement of components in GridLayout manager.

3.4.2 Benefits and Drawbacks
The advantages of GridLayout manager are as follows:

Simple to use.

Useful for grouping components in a rectangular pattern.

V 1.0 © Aptech Limited

Concepts

Figure 3.9: Arrangement of Components - GridLayout

Session

3
Layout Managers

Each component is of same size.

The disadvantage of GridLayout manager is:

Cannot create a complex layout like GridBagLayout where a cell can span more than one row or
column.

3.5 CardLayout Manager
The CardLayout Manager allows the user to stack components one behind another like a deck of cards.
Only one component is visible at a time and that is the component on top. To display other components,
the user has to flip them based on some event like buttons being clicked, or a drop-down to choose a
particular one.
Figure 3.10 displays the CardLayout.

Figure 3.10: CardLayout
The CardLayout manager can be created using one of the constructors shown in table 3.6.

Constructor

CardLayout ()

Constructs the card layout
with no gaps.

CardLayout(int
horizontal _ gap, int
vertical _ gap)

Concepts

Description

Example
CardLayout layout;

layout = new CardLayout();
Constructs the card layout
/* Card layout manager
with the specified horizontal with horizontal gap of 10
and vertical gaps.
pixels and vertical gap of 15
pixels */
CardLayout layout;
layout = new
CardLayout(10,15);

Table 3.6: Constructors of CardLayout Manager

V 1.0 © Aptech Limited

3

Session

Layout Managers

3.5.1 Creating Layout and Adding Components
To set the layout of a container to CardLayout manager, invoke the setLayout() method of the
container. An instance of the CardLayout class is sent as its argument. Once the container is governed
by the CardLayout manager, you create the cards. These cards are typically panels with their associated
components and then add them to the container.
The add() method of the container accepts two arguments. The first argument is the card and the
second argument is a string specifying the name of the card.
Code Snippet 3 shows how to set the layout of the panel to card layout and add the panels to the main
panel.
Code Snippet 3:
CardLayout cardLayout; JPanel pnlSubjects;
JPanel pnlEnglish, pnlScience, pnlMaths;
// Creates the card layout manager
cardLayout = new CardLayout();
// Creates a main panel
pnlSubjects = new JPanel();
// Sets the layout of the panel
pnlSubjects.setLayout(cardLayout);
// Creates panels representing three cards
pnlEnglish = new JPanel();
pnlScience = new JPanel();
pnlMaths = new JPanel();

Concepts

Figure 3.11 shows the output of Code Snippet 3.

Figure 3.11: Output – Panel

V 1.0 © Aptech Limited

Session

3
Layout Managers

3.5.2 Flipping Components
The components of a CardLayout manager can be flipped by the following methods as shown in table
3.7:

Methods

void first(Container
parent)

void next(Container
parent)

Description
Makes the first card of the
container visible, where parent
is the container governed by
the CardLayout manager.

Example

// Creates the card
layout manager
CardLayout cl = new
CardLayout();
. . .

// Make the first
card visible
cl.first(pnlCards);
Makes the next card of the // Creates the card
layout manager
container visible.
CardLayout cl = new
CardLayout();
. . .

void
previous(Container
parent)

// Makes the next
card visible
cl.next(pnlCards);
Makes the previous card of the // Creates the card
layout manager
container visible.
CardLayout cl = new
CardLayout();
. . .
// Makes the previous

void last(Container
parent)

// card visible
cl.previous(pnlCards);
Makes the last card of the // Creates the card
layout manager
container visible.
CardLayout cl = new
CardLayout();

Concepts

. . .
// Makes the last card
//visible
cl.last(pnlCards);

Table 3.7: Methods of Flipping Components in CardLayout Manager
V 1.0 © Aptech Limited

3

Session

Layout Managers

3.5.3 Benefits and Drawbacks
The advantages of using CardLayout manager are as follows:

Allows several containers and their associated components to share the same space in the
container.

The disadvantages of using CardLayout manager are as follows:

Not visually appealing as a Tabbed pane.

Requires other components like buttons or drop-down to flip through.

Figure 3.12 shows the benefits and drawbacks of CardLayout manager.

Figure 3.12: CardLayout

3.6 Additional Layout Manager
Swing supports additional layout managers apart from FlowLayout, BorderLayout, GridLayout and
CardLayout. The additional layouts are GridBagLayout, SpringLayout, and Absolute Positioning
(also referred to as null layout).

The GridBagLayout class is the most complex and yet the most flexible layout manager. The
GridBagLayout manager allows the user to place components in rows and columns. However, these
components can span multiple rows or columns. All the rows need not necessarily have the same height,
and all the columns need not necessarily have the same width.
The GridBagLayout manager works by specifying constraints on each component before it is
being laid out. To specify these constraints Swing provides a GridBagConstraints class. The

V 1.0 © Aptech Limited

Concepts

3.6.1 GridBagLayout Manager

Session

3
Layout Managers

GridBagConstraints class has several constraint variables and objects which allows the user to

specify the constraints on the components, before adding components to a container.
The constraints of the GridBagConstraints class are as listed in table 3.8

Constraint

gridx and gridy
gridwidth and
gridheight
fill

ipadx and ipady

Insets
anchor

weightx and
weighty

Description
These constraints specify the row and column. The leftmost column has
gridx = 0, the top row has gridy = 0.
gridwidth specifies how many columns the component will span and
gridheight specifies how many rows the component will span.
The fill constraint determines whether the component will resize
if more space is available then required. Valid values includes:
GridBagConstraints.NONE, GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL and GridBagConstraints.BOTH.
These constraints specify the internal padding to add to the minimum
size of the component if default values are zero. If these constraints are
specified then the width of the component will be at least its minimum
width plus ipadx*2 pixels, and the height of the component will be at
least its minimum height plus ipady*2 pixels.
This constraint is used to specify the external padding. The java.awt.
Insets class is used to specify the gaps in the order top, left, bottom, and
right.
This constraint is used when the component is smaller than the available
display area. This constraint determines where the component is to be
placed within the display area. The GridBagConstraints class defines
constants, such as CENTER, EAST, WEST, NORTH, SOUTH, NORTHEAST,
SOUTHEAST, NORTHWEST, and SOUTHWEST.
The constraint weightx decides how to distribute space among columns.
The constraint weighty decides how to distribute space among rows. This
constraint is helpful when the container is resized. If this constraint is not
set, then all the components will be clubbed at the center of the container.
Table 3.8: Constraints in GridBagLayout Manager

Code Snippet 4 shows how to use the GridBagLayout manager to add seven buttons to produce a
layout.

Concepts

Code Snippet 4:
Container

c;

JButton btnButton1, btnButton2, btnButton3, btnButton4;
JButton btnButton5, btnButton6, btnButton7;
GridBagConstraints gbc;
...

V 1.0 © Aptech Limited

3

Session

Layout Managers

c = getContentPane();
c.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
// Sets the constraints
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
btnButton1 = new JButton(“1”);
c.add(btnButton1, gbc); gbc.gridx = 1;
btnButton2 = new JButton(“2”);
c.add(btnButton2, gbc); gbc.gridx = 2;
btnButton3 = new JButton(“3”);
c.add(btnButton3, gbc); gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
btnButton4 = new JButton(“4”);
c.add(btnButton4, gbc);
gbc.gridx = 2;
gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.fill = GridBagConstraints.VERTICAL;
btnButton5 = new JButton(“5”);
c.add(btnButton5, gbc);

Concepts

gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;

V 1.0 © Aptech Limited

Session

3
Layout Managers

gbc.gridheight = 1; btnButton6 = new JButton(“6”); c.add(btnButton6, gbc);
gbc.gridx = 1;
btnButton7 = new JButton(“7”);
c.add(btnButton7, gbc);
setVisible(true);

Figure 3.13 shows the output for Code Snippet 4.

Figure 3.13: Output – GridBagLayout

3.6.2 Absolute Positioning (Null Layout)
The absolute positioning or null layout allows the user to specify the bounds of the component before
adding it to the container. These bounds include the x and y position in pixels and the width and height
in pixels of the component.
To set the layout to absolute positioning, pass null as argument in the setLayout() method of the
container.
Syntax:
setLayout(null);

Once the layout is set to null, set the bounds of each component before adding it to the container,
otherwise the component will be not visible.

Concepts

Code Snippet 5 demonstrates how to add components using absolute positioning.
Code Snippet 5:
Container container; JButton btnClick; JTextField txtText;
...
container = getContentPane(); container.setLayout(null);
btnClick = new JButton(“Click”);

V 1.0 © Aptech Limited

3

Session

Layout Managers

btnClick.setBounds(50,50,75,25);
container.add(btnClick);
txtText = new JTextField();
txtText.setBounds(130,50,200,25); container.add(txtText);

3.7 New Layout Manager
A few new layout managers have been added to Swings - BoxLayout and SpringLayout.

3.7.1 BoxLayout Manager
The BoxLayout is similar to a FlowLayout manager except that it places the components on top of
each other in one column, or places them horizontally in a row.
BoxLayout depends on the following axis parameters for the layout:

X _ AXIS: Components are arranged horizontally from left to right.

Y _ AXIS: Components are arranged vertically from top to bottom.

Line _ AXIS: Components are arranged the way words are arranged in a page.

Page _ AXIS: Components are arranged the way text lines are arranged in a page.

Code Snippet 6 demonstrates how to add components using BoxLayout manager by setting the Y_AXIS

parameter.

Code Snippet 6:
...
public class BoxLayoutManager
{

public BoxLayoutManager(){

public static void main(String args[])
{

JPanel container = new JPanel();

V 1.0 © Aptech Limited

Concepts

}

3

Session

Layout Managers

container.setBorder(BorderFactory.createTitledBorder(“BoxLayout”));
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS); container.
setLayout(layout);
...
}

JButton button = new JButton(“Button1”); container.add(button);

button = new JButton(“Button2”); container.add(button);

button = new JButton(“Button3”); container.add(button);

button = new JButton(“Button4”); container.add(button);

3.7.2 SpringLayout
A SpringLayout works by defining relationships or constraints between the edges of components.
Distances between edges are represented by spring objects. Each spring has four properties it’s
minimum, preferred, and maximum values, and its actual (current) value. The springs associated with
each component are collected into a SpringLayout.Constraints object.
Each constraint controls the vertical or horizontal distance between edges of two components. The edges
can be attributed to any child of the container or to the container itself. The x-coordinate of a component
can be expressed using a constraint that controls the distance between the west and east edges of the
component. The west edge is the left side and the east edge is the right side. The y-coordinate of a
component can be expressed by setting the distance between the north edge of the component and the
north edge of its container. The north edge is the top edge and the south edge is the bottom edge.
The method putConstraint() is used to set the constraint between edges of two components or between
edges of a component and the container.
Syntax:
public void putConstraint(String edge1, Component comp1, int distance, String
edge2, Component c2)

Where,
edge1: edge of current component.

Concepts

comp1: the current component.
distance: the fixed distance between components/container.
edge2: the edge of the anchor component/container.
comp2: anchor component/container.

V 1.0 © Aptech Limited

3

Session

Layout Managers

Note -

The edge name, edge1/edge2 can be SpringLayout.NORTH, SpringLayout.SOUTH,
SpringLayout.EAST, or SpringLayout.WEST.

The anchor can be either a component or the container itself with respect to which the
relationship to a component is set.

Code Snippet 7 demonstrates how to add components using SpringLayout manager.

Concepts

Code Snippet 7:

V 1.0 © Aptech Limited

Session

3
Layout Managers

...
/** Defining SpringLayout manager **/
public class SpringLayoutManager extends JFrame{ public SpringLayoutManager(Str
ing title) {
super(title);
Container content_pane = this.getContentPane();
// Create an instance of SpringPanel. SpringPanel spring_panel = new
SpringPanel();
// Add it to frame content_pane.add (spring_panel); setSize(300, 200);
setVisible(true);
}
public static void main(String[] args){
SpringLayoutManager slm = new SpringLayoutManager(“Spring Layout Manager”);
}}
/** Layout five buttons using a SpringLayout Manager. **/
class SpringPanel extends JPanel {
//**
The Constructor creates 5 buttons
and constrains each to a particular position relative
to the panel.
**/
SpringPanel () {
SpringLayout layout = new SpringLayout (); setLayout (layout);
JButton btn1 = new JButton (“Button1”); JButton btn2 = new JButton (“Button2”);
JButton btn3 = new JButton (“Button3”); JButton btn4 = new JButton (“Button4”);
JButton btn5

Concepts

= new JButton (“Button5”);
add (btn1); add (btn2); add (btn3); add (btn4); add (btn5);
// Set the distances between the edges

V 1.0 © Aptech Limited

3

Session

Layout Managers

// Put the first button at pixel co-ordinates (10,10)
// relative to the panel’s frame.
layout.putConstraint (SpringLayout.WEST, btn1, 10, SpringLayout.WEST, this);
layout.putConstraint (SpringLayout.NORTH, btn1, 10, SpringLayout.NORTH,
this);d
Put the second button 5 pixels to the right of the
// First button and 20 pixels below the top panel edge.
layout.putConstraint (SpringLayout.WEST,
btn1);

btn2, 5,

SpringLayout.EAST,

layout.putConstraint (SpringLayout.NORTH, btn2, 20,SpringLayout.NORTH, this);

// Put the third button 50 pixels to the left of the
// panel edge and 20 pixels above the second button. layout.putConstraint
(SpringLayout.WEST, btn3,50, SpringLayout.WEST,
this);
layout.putConstraint (SpringLayout.NORTH, btn3, 20, SpringLayout.SOUTH, btn2);
// Put the fourth button 50 pixels to the right of the
// third button
and 20 pixels below the top panel edge. layout.putConstraint
(SpringLayout.WEST, btn4,50, SpringLayout.EAST,
btn3);
layout.putConstraint (SpringLayout.NORTH, btn4,20, SpringLayout.NORTH, this);
// Put the fifth button 50 pixels to the right of the
// fourth button and 10 pixels below it.
layout.putConstraint (SpringLayout.WEST, btn5, 50, SpringLayout.EAST, btn4);
layout.putConstraint (SpringLayout.NORTH, btn5, 10,SpringLayout.SOUTH, btn4);
}

Concepts

}

V 1.0 © Aptech Limited

Session

3
Layout Managers

Figure 3.14 shows the output for Code Snippet 7.

Figure 3.14: Output - Code Snippet 7

3.7.3 GroupLayout Class
The GroupLayout class helps in grouping components for better positioning within a container. The
components can be grouped hierarchically in sequential groups or parallel groups. The GroupLayout was
developed for GUI builders, such as Matisse and NetBeans IDE. It works well for manual coding as well as
suits GUI builder requirements.
The layout for GroupLayout class is defined independently for each dimension. This means the vertical
and horizontal layouts are handled separately. Focusing on one dimension at a time is easier than
handling both at the same time. It is important to define each component twice in this layout or else the
GroupLayout class will throw an exception.
GroupLayout class uses two types of arrangements - sequential and parallel, combined with hierarchical

Concepts

composition.

Sequential Arrangement
In a sequential group the components are placed one after another, similar to BoxLayout or FlowLayout along one axis. The position of each component is relative to the previous component.

V 1.0 © Aptech Limited

3

Session

Layout Managers

Parallel Arrangement
Parallel grouping arranges components on top of each other in the same space. Alignment of the
components can be specified along the vertical axis or the horizontal axis or both.

To prevent overlapping of components, they are placed sequentially in one dimension and in parallel in
the other dimension. This nesting of these two arrangements is very effecting.
Code Snippet 8 shows how to layer three components in a sequence.
Code Snippet 8:
horizontal layout = sequential group { c1, c2, c3 }
vertical layout = parallel group (BASELINE) { c1, c2, c3 }.

Code Snippet 9 shows how to add a component parallel to the component c3.
Code Snippet 9:
horizontal layout = sequential group { c1, c2, parallel group (LEFT) { c3, c4 } }
vertical layout = sequential group { parallel group (BASELINE) { c1, c2, c3 }, c4 }

3.7.4 Dimension Class
Many of the methods of the Swing components which receives or returns size, uses an object of the
Dimension class. This is a convenience class to encapsulate the width and height of the component.
The Dimension class takes two integers as parameter, the width and the height. The Dimension class
has two methods, getWidth() and getHeight() which return the width and height. Generally, these
methods are invoked by the layout managers.
Syntax:
public double getWidth()

where,
double: Width of this instance returned by the method in double precision.
Syntax:
public double getHeight()
double: Is the height of this instance returned by the method in double precision.

Code Snippet 10 demonstrates the use of Dimension class in a JButton instance, btnOk. The preferred
size of btnOk has been set using the Dimension class.

V 1.0 © Aptech Limited

Concepts

where,

Session

3
Layout Managers

Code Snippet 10:
JButton btnOk;
...
btnOk = new JButton(“OK”); btnOk.setMinimumSize(new Dimension(50,20));
btnOk.setMaximumSize(new Dimension(70,25)); btnOk.setPreferredSize(new
Dimension(60,25));

3.8 Custom Layout Manager
A custom layout manager is created only if none of the existing layout managers meet the given
requirements. In particular, layout managers like GridBagLayout, SpringLayout, and BoxLayout
are flexible enough to work in most cases.

3.8.1 Implementing the Custom Layout Manager
The LayoutManager interface has five methods that must be implemented by a custom layout. These
five methods are listed in table 3.9.

Method

void addLayoutComponent
(String name, Component
comp)
void removeLayoutCompon
ent(Component)

Description
This method adds the component to the layout and
associate them with the string.

This method is called by the Container methods remove
and removeAll.
Dimension preferredLayo This is called by the Container class’s
utSize(Container)
getPreferredSize() method.

Concepts

Assuming that the components will be at or above their
preferred sizes, this method is required to calculate and
return the ideal container size. This method should also
consider the internal borders of the container.
Dimension minimumLayout This is called by the container’s setMinimumSize()
Size(Container)
method.
Assuming the components will be at or above their
minimum specified size; this method calculates and returns
the minimum container size. This method also considers
the internal borders of the container.

V 1.0 © Aptech Limited

3

Session

Layout Managers

Method

Description

void layoutContainer(Co This is called to size and position the components in a
ntainer)
container.

The layoutContainer method does not draw
components. It invokes one or more of the following
components methods to set the component size
and position: setSize(), setLocation(),and
setBounds().
This method should consider the container’s internal
borders, and also take into account the container’s
orientation (returned by the getComponentOrientatio
n()method.
Table 3.9: Methods of Custom Layout Manager
Code Snippet 11 demonstrates how to create the DiagonalLayout manager.
Code Snippet 11:
import java.awt.*;
public class DiagonalLayout implements LayoutManager {
private int vgap;
private int minWidth = 0, minHeight = 0;
private int preferredWidth = 0, preferredHeight = 0;
private boolean sizeUnknown = true;
public DiagonalLayout() {
this(5);
}
public DiagonalLayout(int v) {
vgap = v;
}
public void addLayoutComponent(String name, Component comp) {
}
/* Required by LayoutManager. */
public void removeLayoutComponent(Component comp) {
}

V 1.0 © Aptech Limited

Concepts

/* Required by LayoutManager. */

Session

3
Layout Managers

private void setSizes(Container parent) {
int nComps = parent.getComponentCount();
Dimension d = null;
// Reset preferred/minimum width and height.
preferredWidth = 0;
preferredHeight = 0;
minWidth = 0;
minHeight = 0;
for (int i = 0; i < nComps; i++) {
Component c = parent.getComponent(i);
if (c.isVisible()) {
d = c.getPreferredSize();
if (i > 0) {
preferredWidth += d.width/2;
preferredHeight += vgap;
} else {
preferredWidth = d.width;
}
preferredHeight += d.height;
minWidth = Math.max(c.getMinimumSize().width,
minWidth);
minHeight = preferredHeight;

Concepts

}

}

}
/* Required by LayoutManager. */
public Dimension preferredLayoutSize(Container parent) {

V 1.0 © Aptech Limited

3

Session

Layout Managers

Dimension dim = new Dimension(0, 0);
int nComps = parent.getComponentCount();
setSizes(parent);
//Always add the container’s insets!
Insets insets = parent.getInsets();
dim.width = preferredWidth
+ insets.left + insets.right;
dim.height = preferredHeight
+ insets.top + insets.bottom;
sizeUnknown = false;
return dim;
}
/* Required by LayoutManager. */
public Dimension minimumLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
int nComps = parent.getComponentCount();
//Always add the container’s insets!
Insets insets = parent.getInsets();
dim.width = minWidth
+ insets.left + insets.right;
dim.height = minHeight
+ insets.top + insets.bottom;
sizeUnknown = false;
return dim;
}
/*
* This is called when the panel is first displayed,
* and every time its size changes.

V 1.0 © Aptech Limited

Concepts

/* Required by LayoutManager. */

Session

3
Layout Managers

* Note: You CAN’T assume preferredLayoutSize or
* minimumLayoutSize will be called -- in the case
* of applets, at least, they probably won’t be.
*/
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int maxWidth = parent.getWidth()
- (insets.left + insets.right);
int maxHeight = parent.getHeight()
- (insets.top + insets.bottom);
int nComps = parent.getComponentCount();
int previousWidth = 0, previousHeight = 0;
int x = 0, y = insets.top;
int rowh = 0, start = 0;
int xFudge = 0, yFudge = 0;
boolean oneColumn = false;
// Go through the components’ sizes, if neither
// preferredLayoutSize nor minimumLayoutSize has
// been called.
if (sizeUnknown) {
setSizes(parent);
}
if (maxWidth <= minWidth) {
oneColumn = true;
}

Concepts

if (maxWidth != preferredWidth) {
xFudge = (maxWidth - preferredWidth)/(nComps - 1);
}
x += previousWidth/2 + xFudge;

V 1.0 © Aptech Limited

3

Session

Layout Managers

}
y += previousHeight + vgap + yFudge;
}
if (maxHeight > preferredHeight) {
yFudge = (maxHeight - preferredHeight)/(nComps - 1);
}
for (int i = 0 ; i < nComps ; i++) {
Component c = parent.getComponent(i);
if (c.isVisible()) {
Dimension d = c.getPreferredSize();
// increase x and y, if appropriate
if (i > 0) {
if (!oneColumn) {
// If x is too large,
if ((!oneColumn) &&
(x + d.width) >
(parent.getWidth() - insets.right)) {
// reduce x to a reasonable number.
x = parent.getWidth()
- insets.bottom - d.width;
}
// If y is too large,
if ((y + d.height)
> (parent.getHeight() - insets.bottom)) {
// do nothing.
}
// Set the component’s size and position.
c.setBounds(x, y, d.width, d.height);

V 1.0 © Aptech Limited

Concepts

// Another choice would be to do what we do to x.

Session

3
Layout Managers

previousWidth = d.width;
previousHeight = d.height;
}
} }
public String toString() {
String str = “”;
return getClass().getName() + “[vgap=” + vgap + str + “]”;
}}

Figure 3.15 shows a DiagonalLayout manager generated by Code Snippet 11.

Figure 3.15: DiagonalLayout Manager

3.9 Decorate Swing Components

Concepts

Though window decorations are provided by native window system, you can customize them by specifying
a look and feel such as Windows look and feel or Java look and feel. This provides the flexibility to the
programmer to provide own decorations or no decorations at all and also manage the screen size (fit to
width or full screen mode).

3.9.1 JLayer Class
The javax.swing.JLayer class acts as a universal decorator for all swing components. JLayer allows
the user to draw on components and respond to the component events without disturbing the integrity
of the underlying components.
The javax.swing.JLayer class and javax.swing.plaf.LayerUI class work together. The
V 1.0 © Aptech Limited

3

Session

Layout Managers

component to be decorated is the target when creating a custom drawing.
To decorate the component, perform the following steps:

Create the target component.

Create an instance of a LayerUI subclass to do the drawing.

Create a JLayer object that wraps the target and the LayerUI object.

Use the JLayer object in your user interface just as you would use the target component.

Code Snippet 12 shows how to decorate the JPanel object.
Code Snippet 12:
JFrame f = new JFrame();
JPanel panel = createPanel();
f.add (panel);

Frame f = new JFrame();
JPanel panel = createPanel();
LayerUI<JPanel> layerUI = new MyLayerUISubclass();
JLayer<JPanel> jlayer = new JLayer<JPanel>(panel, layerUI);
f.add (jlayer);

Custom decoration and event handling for a JLayer object is taken care of by the LayerUI class.
When an instance of the LayerUI is created, the custom behavior can be applied to all the objects with
a generic type. Therefore, there is no need to create a JLayer subclass as all the custom behavior is
contained in the LayerUI class.
In turn, the LayerUI class inherits all of its behavior from the ComponentUI class. The JLayer class
is usually generic with the exact type of its view component. On the other hand, the LayerUI class is
designed for use with JLayer classes of its generic parameter or any of its ancestors.

V 1.0 © Aptech Limited

Concepts

3.9.2 LayerUI Class

Session

3
Layout Managers

Table 3.10 shows the most commonly overridden methods.

Method

paint(Graphics g, JComponent c)
super.paint(g, c)

installUI(JComponent c)
uninstallUI(JComponent c)

Description
This method draws the target component.
This method renders the target component the
same way as swing.
This method is called to initialize a component
associated with the LayerUI subclass.
This method is called when the component is no
longer associated with the LayerUI subclass.

Table 3.10: Methods of LayerUI Class

3.9.3 Drawing on Components
A good LayerUI subclass is needed to use the JLayer class. The LayerUI class changes how components
are drawn.
Code Snippet 13 shows how to paint a transparent color gradient on a component.

Concepts

Code Snippet 13:

V 1.0 © Aptech Limited

3

Session

Layout Managers

class WallpaperLayerUI extends LayerUI<JComponent> {
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Graphics2D g2 = (Graphics2D) g.create();
int w = c.getWidth();
int h = c.getHeight();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .5f));
g2.setPaint(new GradientPaint(0, 0, Color.yellow, 0, h, Color.red));
g2.fillRect(0, 0, w, h);
g2.dispose();
}
}

The paint () method is where the custom drawing takes place. The call to the super.paint()
method draws the contents of the JPanel object. After setting up a 50% transparent composite, the
color gradient is drawn.

3.9.4 Create Translucent and Shaped Windows
Java Swing also supports creation of translucent and shaped windows in applications.
Translucency for windows: Make the full window translucent with a specified alpha level.
Per pixel translucency: Make part of window translucent.

To Implement Uniform Translucency

Invoking the setOpacity(float) method allows the user to create a window where each pixel
has the same translucency. The translucency of the window is represented by the float argument
which should be a value between 0 and 1. For greater transparency, set the value lower.
Code Snippet 14 shows how to check if a device supports translucency.

V 1.0 © Aptech Limited

Concepts

Shaped windows: Create windows with a certain shape such as circle, oval, and so on.

Session

3
Layout Managers

Code Snippet 14:
// Determine if the GraphicsDevice supports translucency.
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
//If translucent windows aren’t supported, exit.
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println(
“Translucency is not supported”);
System.exit(0);
}

Code Snippet 15 shows how to create a window with 55% opaqueness.
Code Snippet 15:
// Create window with 55% opaqueness.
package com.mycompany.java7.swing;
import javax.swing.*;
import java.awt.*;
public class TranslucentWindowExample extends JFrame {
super(“TranslucentWindow”);
setSize(300, 200);

Concepts

setDefaultCloseOperation(EXIT_ON_CLOSE);

V 1.0 © Aptech Limited

3

Session

Layout Managers

getRootPane().setDoubleBuffered(false);
setOpacity(0.55f);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
If(ge.getDefaultScreenDevice().isWindowTranslucencySupported(GraphicsD
evice.WindowTranslucency.TRANSLUCENT)){
new TranslucentWindow();
}
}
});
}
}

Concepts

Figure 3.16 shows a window with 55% opaqueness.

Figure 3.16: Opaque Window

V 1.0 © Aptech Limited

3

Session

Layout Managers

To Implement Per Pixel Translucency

Implementing per pixel translucency involves defining alpha values for the area that a window
occupies. When the alpha value is zero, the window is fully transparent. When the alpha value is
255, the window is fully opaque. All values in between have a gradual increase in transparency. The
gradientPaint class allows the user to create a smooth interpolation between alpha values. The
isOpaque method helps to find out if a window is using per pixel translucency.
Here are the steps required to implement the isOpaque method:

Invoke setBackground(new Color(0,0,0,0)) on the window.

Create a JPanel instance that overrides the paintComponent method.

In the paintComponent method, create a GradientPaint instance.

Set the GradientPaint instance as the panel’s paint method.

Code Snippet 16 shows how to create a gradient window.
Code Snippet 16:
setBackground(new Color(0,0,0,0));
setSize(new Dimension(300,200));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
if (g instanceof Graphics2D) {
final int R = 240;
final int G = 240;
final int B = 240;

Concepts

Paint p =
new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
0.0f, getHeight(), new Color(R, G, B, 255), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());

V 1.0 © Aptech Limited

3

Session

Layout Managers

}
}
};

To Create a Shaped Window

The setShape() method allows the user to create a shaped window. The shape argument passed
determines how the window is clipped. It is better to set the shape to undecorated windows as
window decoration cannot be re-formed for the new shape.
To set the window’s shape, the best practice is to invoke setShape() in the componentResized()
method of the component event listener. This makes sure that the shape is calculated correctly for
the actual size of the window.
Code Snippet 17 shows how to implement shaped windows.
Code Snippet 17:
addComponentListener(new ComponentAdapter() {
// Give the window an elliptical shape.
// If the window is resized, the shape is recalculated here.
@Override
public void componentResized(ComponentEvent e) {
setShape(new Ellipse2D.Double(0,0,getWidth(),getHeight()));
}
});
setUndecorated(true);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (!gd.isWindowTranslucencySupported(PERPIXEL_TRANSPARENT)) {
System.err.println(“Shaped windows are not supported”);

Concepts

System.exit(0);
}

V 1.0 © Aptech Limited

Session

3
Layout Managers

Figure 3.17 shows a shaped window.

Figure 3.17: Shaped Window

3.9.5 Responding to Events
All the events from the related components need to be received and processed. LayerUI subclass
can receive all the events, but it has to register for specific events it’s interested in. This is set by
setLayerEventMask() method.
All events going to your JLayer subclass get routed to an event handler method whose name matches
the event type.
The setLayerEventMask() method is called to indicate the LayerUI subclass’s willingness in receiving
the mouse and mouse motion events.
Code Snippet 18 shows a portion of LayerUI subclass that registers to receive mouse events.
Code Snippet 18:
public void installUI(JComponent c) {
super.installUI(c);
JLayer jlayer = (JLayer)c;
jlayer.setLayerEventMask(

Concepts

AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK
);

V 1.0 © Aptech Limited

3

Session

Layout Managers

3.9 Check Your Progress
Which of these statements about the Layout Managers are true?
A.
B.
C.
D.
E.

The setVisible() method is responsible for invoking the pack() method before
the window frame is put in the realized state.
The getPreferredSize() method is invoked recursively for all the components until
the total size of the frame is computed.
The FlowLayout manager arranges the components from right to left.
The GridLayout manager arranges the components in terms of rows and columns.
The BorderLayout manager allows to position components in only four possible
locations in a container.

(A) A, B, and C
(B) C, D, and E
2.

A, B, and D
A, C, and D

Which of these statements about FlowLayout manager are true?
A.
B.
C.
D.
E.

The FlowLayout manager uses the preferred size of the components when they are laid
in a container.
If the container is wider than necessary for a row of components, then the row is
centered by default.
One cannot specify the alignment for a component when using FlowLayout manager.
If the container is resized or loses the original alignment, some components make go up
or down depending upon the width.
FlowLayout manager can achieve complex alignment.

(A) A and B
(B) C and E
3.

(C)
(D)

(C)
(D)

A, B, and D
A, C, and D

You are trying to set the FlowLayout manager with left alignment and add JLabel to the container.
Which of the following code will help you to achieve this?
A. JLabel lblName;
JLabel(“Name”);

B.

setLayout(new FlowLayout()); lblName = new

getContentPane().add(lblName);
JLabel lblName;
setLayout(new
FlowLayout(FlowLayout.LEFT));
lblName
JLabel(“Name”); getContentPane().add(lblName);

V 1.0 © Aptech Limited

=

new

Concepts

1.

Session

3
Layout Managers
C.

JLabel lblName; setLayout(new FlowLayout());
lblName = new JLabel(“Name”, FlowLayout.LEFT);

D.

getContentPane().add(lblName);
JLabel lblName;
SetLayout(new
FlowLayout(FlowLayout.LEFT));
lblName
JLabel(“Name”); getContentPane().add(lblName);

4.

A BorderLayout manager allows to add only 6 components.
By default the component is added to the center if the direction is not specified.
You cannot specify the direction where the component is to be placed.
The center component stretches both horizontally and vertically.
JFrame and JDialog have the BorderLayout Manager.

(A) A, B, and C
(B) C, D, and E

(C)
(D)

B, D, and E
A, C, and D

You are trying to set the layout of the JPanel to the border layout and add JLabel to the north
direction of the JPanel. Which of the following code will help you to achieve this?
A. JPanel pnlPanel; JLabel lblStatus;
pnlPanel = new JPanel(); pnlPanel.setLayout(new BorderLayout());
lblStatus = new JLabel(“Status”);

B.

pnlPanel.add(lblStatus,NORTH);
JPanel pnlPanel; JLabel lblStatus;
pnlPanel = new JPanel(); pnlPanel.setLayout(new BorderLayout());
lblStatus = new JLabel(“Status”);

C.

add(lblStatus,BorderLayout.NORTH);
JPanel pnlPanel; JLabel lblStatus;
pnlPanel = new JPanel(); pnlPanel.setLayout(new BorderLayout());
lblStatus = new JLabel(“Status”);

Concepts

new

Which of the statements about BorderLayout manager are true?
A.
B.
C.
D.
E.

5.

=

D.

pnlPanel.add(lblStatus, BorderLayout.NORTH);
JPanel pnlPanel; JLabel lblStatus;
pnlPanel = new JPanel();
pnlPanel.setLayout(new BorderLayout(BorderLayout.NORTH));
lblStatus = new JLabel(“Status”); pnlPanel.add(lblStatus);

V 1.0 © Aptech Limited

3

Session
6.

Layout Managers

Which of the statements about GridLayout manager are true?
A.
B.
C.
D.
E.

The GridLayout manager makes all components of same size.
The GridLayout manager is useful for grouping components in a rectangular pattern.
GridLayout is typically used when all the components in the container are meant to be
of the different size.
You cannot have gaps between components in GridLayout manager.
If the container is resized then the available space is uniformly distributed.

(A) A, B, and E
(B) C, D, E
7.

(C)
(D)

A, B, and D
A, C, and D

You are trying to set the layout of the panel to grid layout and add buttons labeled 0 to 9 in four rows
and three columns. Which of the following code will help you to achieve this?
A.

JPanel pnlNumericPad;
JButton

btnOne, btnTwo, btnThree, … btnNine, btnZero;

pnlNumericPad = new JPanel(); pnlNumericPad.setLayout
(new GridLayout(4, 3));
btnOne = new JButton(“1”); pnlNumericPad.add(btnOne);
btnTwo = new JButton(“2”); pnlNumericPad.add(btnTwo);
. . .
. . .

B.

btnZero = new JButton(“0”); pnlNumericPad.add(btnZero);
JPanel pnlNumericPad;
JButton
btnOne,
btnTwo,
btnThree,

btnNine,
btnZero;
pnlNumericPad
=
new
JPanel();
pnlNumericPad.SetLayout(new
Gridlayout(4, 3));
btnOne = new JButton(“1”); pnlNumericPad.add(btnOne); btnTwo =
new JButton(“2”); pnlNumericPad.add(btnTwo);
. . .
btnZero = new JButton(“0”); pnlNumericPad.add(btnZero);

V 1.0 © Aptech Limited

Concepts

. . .

Session

3
Layout Managers
C.

JPanel pnlNumericPad;
JButton
btnOne,
btnTwo,
btnThree,

btnNine,
btnZero;
pnlNumericPad
=
new
JPanel();
pnlNumericPad.setLayout(new
Gridlayout(3,4));
btnOne = new JButton(“1”); pnlNumericPad.add(btnOne); btnTwo =
new JButton(“2”); pnlNumericPad.add(btnTwo);
. . .
. . .

D.

btnZero = new JButton(“0”); pnlNumericPad.add(btnZero);
JPanel pnlNumericPad;
JButton
btnOne,
btnTwo,
btnThree,

btnNine,
btnZero;
pnlNumericPad
=
new
JPanel();
pnlNumericPad.setLayout(new
Gridlayout(3,4));
btnOne = new JButton(“1”); add(btnOne);
btnTwo = new JButton(“2”); add(btnTwo);
. . .
. . .

Concepts

btnZero = new JButton(“0”); add(btnZero);

V 1.0 © Aptech Limited

3

Session

Layout Managers

3.9.1 Answers
C
C
B
C
C
A
A

Concepts

1.
2.
3.
4.
5.
6.
7.

V 1.0 © Aptech Limited

Session

3
Layout Managers

Summary
A layout manager is a Java object associated with a container which governs the placement and
size of the component when it is added to a container.

The FlowLayout manager lays the components in a row from left to right in a container. The
FlowLayout manager uses the preferred size of the components when they are laid in a container.

The BorderLayout manager allows you to add components in the east, west, north, south, and
center direction of a container. By default, if the direction is not specified then the component is
placed in the center.

The GridLayout manager places the components in terms of rows and columns. Each cell where
the row and column meet is of the same size. If the container is resized, then the available space is
again distributed uniformly amongst all the cells.

The CardLayout manager allows you to stack components one behind another like a deck of cards.
Only one component is visible at a time and that is the component on top. To display other
components one has to flip them.

The CustomLayout manager is built only when no other existing Layout manager meets the given
requirements. The custom layout manager is built under a class that implements the
LayoutManager interface.

There are new Layout managers in Swing, such as BoxLayout Manager, SpringLayout Manager, and
GroupLayout class. These allow you to place components in columns; rows are by defining
relationships between components.

The javax.swing.JLayer class acts as a universal decorator for all swing components.

Concepts

V 1.0 © Aptech Limited

Session 4
Menu Components
Welcome to the Session, Menu Components.
This session provides a brief introduction to the menu system and its
various components, such as menu bar, menus, and menu items. Further,
the session introduces file dialog box that allows to select a file or directory
from the operating system. Finally, the session explains the toolbar
component that is used to display icons instead of textual menus.
In this Session, you will learn to:

Describe JMenuBar and its methods

Describe and explain JMenu and JMenuItem

Describe and explain JCheckBoxMenuItem and JRadioButtonMenuItem

Describe JPopupMenu and its methods

Explain JFileChooser and its use

Explain and state the syntax of the methods of JFileChooser

Explain how to filter files in JFileChooser and also how to subclass it

Explain JToolBar

State the syntax of the methods of JToolBar

4

Session

Menu Components

4.1 Introduction
Typically an application’s GUI should expose the components required to depict the main feature of the
application. However, several actions such as new, open, save, exit, and so on are not directly related to the
feature of the application. However, these actions are still required to complete the overall functionality
of the application.
If there were no menu system, then the application’s GUI would have been clustered with several
components to perform these trivial actions. A menu system provides a convenient alternative means to
handle these actions not directly associated with the application’s main feature.

4.1.1 Menu System
A menu system provides a menu bar below the Window’s title bar. This bar contains items called a menu.
When you click a menu it drops down and displays various choices called menu items.
Each of these menu items is associated with actions to perform desired action. You can choose the task
by clicking a menu item.
Alternately, the GUI provides a popup menu, which is invisible at first sight. When you right click the
mouse on the screen, a menu containing menu items pops up besides where you clicked the mouse. It
allows you to conveniently choose a desired task.

Figure 4.1: Menu System

4.1.2 JMenuBar

A JMenuBar is a class which is used to create a menu bar. You typically see a menu bar in a window just
below the title bar of a frame. A menu bar contains menu items, for example ‘File’, ‘Edit’, ‘View’, and so
on.

V 1.0 © Aptech Limited

Concepts

Figure 4.1 displays the menu system.

Session

4
Menu Components

A menu bar can be created using following constructor of the JMenuBar class:

JMenuBar()

The top level container has setMenuBar() method to add the JMenuBar to it. This method takes
an object of the JMenuBar class as an argument.
Figure 4.2 displays the menu bar.

Figure 4.2: Menu Bar
Code Snippet 1 shows how to create a menu bar and add it to the frame.
Code Snippet 1:
JMenuBar mbrMenuBar;
JFrame frmMenu;
frmMenu = new JFrame(“Menu bar”);
// Creates a menu bar
mbrMenuBar = new JMenuBar();

Concepts

...
// Adds the JMenuBar to the top level container JFrame
frmMenu.setMenuBar(mbrMenuBar);

4.1.3 JMenu
A JMenu is a class used to represent a menu on a menu bar. When you click JMenu it drops down and
isplays one or more items.

V 1.0 © Aptech Limited

4

Session

Menu Components

A menu can be created using any one of the following constructors of the JMenu class:

JMenu() - Constructs a JMenu without a label.

JMenu(String label) - Constructs a JMenu with the specified label.

Figure 4.3 displays the JMenu.

Figure 4.3: JMenu
A JMenu is added to the menu bar using add() method of the JMenuBar. The add() method takes an
object of JMenu class as an argument.
The following Code Snippet 2 shows how to add the ‘File’ menu and ‘Edit’ menu to the menu bar.
Code Snippet 2:
JMenuBar mbrMenuBar;
JMenu mnuFile, mnuEdit;
// Creates a menu bar
mbrMenuBar = new JMenuBar();
...
// Creates a menu with the specified label
mnuEdit = new JMenu(“Edit”);
// Adds the menu to the menu bar
mbrMenubar.add(mnuFile);
mbrMenubar.add(mnuEdit);

V 1.0 © Aptech Limited

Concepts

mnuFile = new JMenu(“File”);

Session

4
Menu Components

The JMenu class has some important methods that are as follows:

public void addSeparator()

The method of the JMenu class is used to append a new separator to the end of the menu. For
example, mnuFile.addSeparator();

public void setMnemonic(int mnemonic)

The method allows one character in the menu label to be underlined. The menu can be displayed
by pressing the Alt key and the mnemonic character combination. For example, a menu with the
label File can be displayed by pressing the Alt + F keys combination.
Syntax:
public void setMnemonic(int mnemonic)

where,

mnemonic: Is an integer argument to represent the numeric key. The class KeyEvent has
constants to represent keys. For example, KeyEvent.VK_C represents the key ‘C’.

Condider the following statement to set the Alt+F key combination as shortcut key�:
mnuFile.setMnemonic(KeyEvent.VK_F);

Concepts

Figure 4.4 displays the mnemonic and separator in the JMenu.

Figure 4.4: Mnemonic and Separator in JMenu

V 1.0 © Aptech Limited

4

Session

Menu Components

4.1.4 Creating a JMenuItem
A JMenuItem is a class which creates an item provided by a menu. You typically add a JMenuItem to a
JMenu.
A menu item has an action associated with it. When you click this item it generates an event and the
action is performed.
A menu item is created using any one of the following constructors of the JMenuItem class:

JMenuItem(String label)

The constructor constructs a menu item with the specified label.
Syntax:
public JMenuItem(String label)

where,

label: Is the string representing name of the menu item.

Consider the following statements to create the menu item ‘New’ with label.
JMenuItem mniNew;
mniNew = new JMenuItem(“New”);

JMenuItem(String label, Icon icon)

The constructor constructs a menu item with the specified label and icon.
Syntax:
public JMenuItem(String label, Icon icon)

where,

label: Is the string representing name of the menu item.
icon: Is a string pointing to a valid image file. Java supports images of type JPEG, GIF, and

PNG.

Consider the following statements to create the menu item ‘Open’ with the label and image icon.
JMenuItem mniOpen;

Concepts

mniOpen = new JMenuItem(“Open”, new ImageIcon(“Open.gif”));

V 1.0 © Aptech Limited

Session

4
Menu Components

Figure 4.5 displays the JMenuItem.

Figure 4.5: JMenuItem

4.1.5 Methods of JMenuItem
The JMenuItem class has following important methods:

public void setEnabled(boolean enable)

The method is used to enable or disable the menu item.
Syntax:
public void setEnabled(boolean enable)

where,

enable: If set to true then menu item is enabled. If set to false then menu item is disabled.

The following code snippet shows how to enable the menu item ‘Open’. For example, mniOpen.
setEnabled(true);

public void setMnemonic (int mnemonic)

Concepts

The method is used to set the mnemonic character.
Syntax:
public void setMnemonic (int mnemonic)

where,

mnemonic: Is an integer argument to represent the numeric key. The class KeyEvent has
constants to represent keys. For example, KeyEvent.VK_N represents the key ‘N’.

V 1.0 © Aptech Limited

4

Session

Menu Components

The following code snippet shows how to set mnemonic for the menu item ‘Open’. For example,
mniOpen.setMnemonic(KeyEvent.VK_O);

public void setAccelerator(KeyStroke keystroke)

The method is used to set the key combination which invokes the menu item’s action listeners
without navigating the menu hierarchy.
Syntax:
public void setAccelerator(KeyStroke keystroke)

where,

keystroke: Is an object of the class KeyStroke which will serve as an accelerator.

Code Snippet 3 shows how to set an accelerator key for the menu item ‘Open’.
Code Snippet 3:
// An int specifying the numeric code for a keyboard key
int key = KeyEvent.VK_O;
// An integer specifying the modifier
int modifier = KeyEvent.ALT_MASK;
KeyStroke keystroke;
// Returns instance of a KeyStroke, given a numeric key code and
// a set of modifiers.
keystroke = KeyStroke.getKeyStroke(key, modifier);
// Sets the key combination which invokes the menu item’s action listeners
mniOpen.setAccelerator(keystroke);

Concepts

Figure 4.6 displays features of the JMenuItem.

Figure 4.6: Features of JMenuItem

V 1.0 © Aptech Limited

Session

4
Menu Components

Note - The JMenuItem class inherits from javax.swing.AbstractButton the following methods

to dynamically change the icon.

setRollOverIcon(Icon icon)

This icon is displayed when the mouse hovers over the menu item

setPressedIcon(Icon icon)

This icon is displayed when the menu item is pressed

setDisabledIcon(Icon icon)

This icon is displayed if the menu item is disabled

setSelectedIcon(Icon icon)

This icon is displayed when the menu item is selected

4.1.6 Sub-Menus
A menu item is added to the menu using add() method of the JMenu class. The add() method takes an
object of the JMenuItem class as a parameter.
A JMenuItem can be a sub-menu. This sub-menu is called a cascaded menu. They have a triangular icon
pointing rightwards.
To create a sub-menu simply add JMenu in place of a JMenuItem. Adding a JMenu to another JMenu
creates a cascaded menu. A sub-menu (cascaded menu) when clicked displays its set of items.

Concepts

Figure 4.7 displays sub-menu.

Figure 4.7: Sub-menu
V 1.0 © Aptech Limited

4

Session

Menu Components

Code Snippet 4 shows how to add the sub menu ‘Delete’ with the menu items ‘Table’, ‘Columns’, and
‘Rows’ to the ‘Operation’ menu.
Code Snippet 4:
...
JMenu mnuTable,mnuDelete;
JMenuItem mniTable,mniColumns,mniRows;
...
// Adds the menu item to the “Delete” menu.
mnuDelete.add(mniTable);
mnuDelete.add(mniColumns);
mnuDelete.add(mniRows);
...
// Creates sub-menu(cascaded) “Delete” in the “Table” menu.
mnuTable.add(mnuDelete);

Figure 4.8 shows the output for Code Snippet 4.

Figure 4.8: Output - Sub-menu

4.1.7 Event Handling

void actionPerformed(ActionEvent e)

The JMenuItem class has a method add ActionListener(), which is used to register the
listener object.. The code for the action handler of the clicked menu item is specified in the
actionPerformed() method.

V 1.0 © Aptech Limited

Concepts

A menu item component listens using the java.awt.event.ActionListener interface. This interface
has one method:

Session

4
Menu Components

Code Snippet 5 shows how to close the application when the ‘Exit’ menu item is clicked.
Code Snippet 5:
// Event handling of the ‘Exit’ menu item
mniExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Closes the application
System.exit(0);
}
});

4.1.8 JCheckBoxMenuItem
A JCheckBoxMenuItem is similar to a JMenuItem with the additional feature of selecting and deselecting
them.
If JCheckBoxMenuItem is selected, it typically shows a checkmark, and if deselected the checkmark
disappears. A JCheckBoxMenuItem like a JMenuItem can have a text label, an icon, or both.

Concepts

Figure 4.9 displays the JCheckBoxMenuItem.

Figure 4.9: JCheckBoxMenuItem

V 1.0 © Aptech Limited

4

Session

Menu Components

The JCheckBoxMenuItem can be created using any one of the constructors as follows:

JCheckBoxMenuItem(String label)

The constructor constructs an initially unselected check box menu item with the specified label.
Syntax:
public JCheckBoxMenuItem(String label)

where,

label: Is the String instance representing label of the check box menu item.

JCheckBoxMenuItem(String label, boolean select)

The constructor constructs a check box menu item with the specified label and the initial selection.
A tick mark is visible when you set select as true.
Syntax:
public JCheckBoxMenuItem(String label, boolean select)

where,

select: If set to true then the menu item is kept selected when menu is displayed, otherwise

not.

Code Snippet 6 shows how to create the check box menu item ‘Standard’, ‘Formatting’, and ‘Auto
Text’ and add it to the ‘Toolbars’ menu item.
Code Snippet 6:
JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncFormatting,mncAutoText;
// Creates the check box menu item with the label ‘Standard’ and selected
mncStandard = new JCheckBoxMenuItem(“Standard”, true);
// Creates the check box menu item with the label ‘Formatting’ and selected
mncFormatting = new JCheckBoxMenuItem(“Formatting”, true);
// Creates the check box menu item with the label ‘Auto Text’ and selected
// Adds the check box menu item to the ‘Toolbars’ menu item
mniToolbars.add(mncStandard);
mniToolbars.add(mncFormatting);
mniToolbars.add(mncAutoText);

V 1.0 © Aptech Limited

Concepts

mncAutoText = new JCheckBoxMenuItem(“Auto Text”);

Session

4
Menu Components

Figure 4.10 shows the output for Code Snippet 6.

Figure 4.10: Output - JCheckBoxMenuItem
The JCheckBoxMenuItem has following methods:

public boolean isSelected()

The method returns true if the JCheckBoxMenuItem is in selected state, else returns false. A
check box menu item is said to be selected if the tick mark is visible on it.
Syntax:
public boolean isSelected()

where,

boolean: is true if the JCheckBoxMenuItem is in selected state, else false.

Example: To retrieve the state of the check box menu item ‘Formatting’. The statement boolean
select = mncFormatting.isSelected(); is used.

public void setSelected(boolean select)

The method allows you to programmatically set the state of JCheckBoxMenuItem.
Syntax:
public void setSelected(boolean select)

where,

Concepts

select: If set to true then JCheckBoxMenuItem is selected. If set to false then
JCheckBoxMenuItem is deselected.

Example: To set the state of the check box menu item ‘Formatting’ selected. The statement
mncFormatting.setSelected(true); is used.

V 1.0 © Aptech Limited

4

Session

Menu Components

4.1.9 JRadioButtonMenuItem
A JRadioButtonMenuItem is similar to a JRadioButton in appearance and functionality. The only
difference is that a JRadioButtonMenuItem is a menu item and is added to a menu not container.
A JRadioButtonMenuItem, like a JRadioButton can also be added to a ButtonGroup to be
mutually exclusive. If one amongst the group is selected, all others are deselected automatically. A
JRadioButtonMenuItem like a JMenuItem can have a text label, an icon, or both.
Figure 4.11 displays the JRadioButtonMenuItem.

Figure 4.11: JRadioButtonMenuItem

4.1.10 Creating a JRadioButtonMenuItem
The JRadioButtonMenuItem can be created using any one of the constructors described as follows:

JRadioButtonMenuItem(String label)

The constructor constructs a radio button menu item with the specified label.
Syntax:

where,

label: Is the String representing label of the radio button menu item.

JRadioButtonMenuItem(String label, boolean select)

The constructor constructs a radio button menu item with the specified label and the initial
selection.

V 1.0 © Aptech Limited

Concepts

public JRadioButtonMenuItem(String label)

Session

4
Menu Components

Syntax:
public JRadioButtonMenuItem(String label, boolean select)

where,

label: Is the label to be given to the radio button menu item.
select: If set to true then the radio button menu item is kept selected when menu is

displayed otherwise not. A dot is visible when you set select as true.

Code Snippet 7 shows how to create JRadioButtonMenuItem ‘Normal’, ‘Web’, ‘Print’ with the
image icon and add it the ‘View’ menu.
Code Snippet 7:
JMenu mnuView;
JRadioButtonMenuItem mnrNormal, mnrWeb, mnrPrint;
ButtonGroup bgView;
// Creates the radio button menu item with the label NormalLayout selected

mnrNormal = new JRadioButtonMenuItem(“Normal Layout”,true);

// Creates the radio button menu item with the specified label
mnrWeb = new JRadioButtonMenuItem(“Web Layout”);
mnrPrint = new JRadioButtonMenuItem(“Print Layout”;
// Creating ButtonGroup instance
bgView = new ButtonGroup();
// Adds the radio button menu item to the buttongroup
bgView.add(mnrNormal);
bgView.add(mnrWeb);
bgView.add(mnrPrint);
// Adds the radio button menu item to the ‘View’ menu

Concepts

mnuView.add(mnrNormal);

V 1.0 © Aptech Limited

4

Session

Menu Components

Figure 4.12 shows the output for Code Snippet 7.

Figure 4.12: Output - JRadioButtonMenuItem

4.1.11 Methods of JRadioButtonMenuItem
The JRadioButtonMenuItem has following methods:

public boolean isSelected()

The method returns true if the JRadioButtonMenuItem is in selected state, else returns false.
Syntax:
public boolean isSelected()

where,

boolean: Is true if the JRadioButtonMenuItem is in selected state, else false.

Example: To retrieve the state of the JRadioButtonMenuItem instance mnrNormal. The
statement boolean select = mnrNormal.isSelected(); is used.

public void setSelected(boolean select)

The method allows you to programmatically set the state of JRadioButtonMenuItem.
Syntax:
public void setSelected(boolean select)
select: If set to true then JRadioButtonMenuItem is selected. If set to false then
JRadioButtonMenuItem is deselected.

Example: To set the state of the JRadioButtonMenuItem mnrNormal selected. The statement
mnrNormal.setSelected(true);is used.�

V 1.0 © Aptech Limited

Concepts

where,

Session

4
Menu Components

4.1.12 JPopupMenu
A JPopupMenu is menu which pops up when you right-click container. The popup menu appears exactly
at the location where you right clicked.
A JPopupMenu is more convenient than standard menus because it involves less mouse movements.
When you click any where on the container, the menu pops up, allowing you to select an appropriate
item. A JPopupMenu can have submenus.

4.1.13 Creating a JPopupMenu
The JPopupMenu can be created using any one of constructors that are described as follows:

JPopupMenu()

The constructor constructs a popup menu without any title. The statement JPopupMenu mnpPopup
= new JPopupMenu(); creates a popup menu.

JPopupMenu(String title)

Constructs a popup menu with the specified title.
Syntax:
public JPopupMenu(String title)

where,

title: Is the string representing title of the popup menu.

The statement JPopupMenu mnpPopup = new JPopupMenu(“Options”); creates a popup
menu with the title as ‘Options’.

4.1.14 Methods of JPopupMenu
The JPopupMenu has following methods:

JMenuItem add(JMenuItem)

The method adds a menu item at the end of the popup menu.

Concepts

Syntax:
public JMenuItem add(JMenuItem item)

where,

item: Is an object of the class JMenuItem.
JMenuItem: Is an object of the JMenuItem added to the popup menu.

V 1.0 © Aptech Limited

4

Session

Menu Components

Code Snippet 8 shows how to add JMenuItem labeled ‘Cut’, ‘Copy’, and ‘Paste’ to the JPopupMenu.
Code Snippet 8:
JPopupMenu mnpPopup;
JMenuItem mniCut,mniCopy,mniPaste;
// Creates the popup menu
mnpPopup = new JPopupMenu();
// Creates the menu item with label “Cut”
mniCut = new JMenuItem(“Cut”);
// Adds the menu item with label “Cut” to the popup menu
mnpPopup.add(mniCut);
mniCopy = new JMenuItem(“Copy”);
mnpPopup.add(mniCopy);
mniPaste = new JMenuItem(“Paste”);
mnpPopup.add(mniPaste);

void addSeparator()

The method adds a separator at the end of the popup menu.
The statement mnpPopup.addSeparator(); adds a separator at the end of the popup menu.

void setDefaultLightWeightPopupEnabled(boolean)

The method makes the popup a light weight menu if true is used as an argument. Lightweight
popups are more efficient than heavyweight menus.
Syntax:
public
static
lightweight)

void

setDefaultLightWeightPopupEnabled(boolean

where,

The statement JPopupMenu.setDefaultLightWeightPopupEnabled(true); makes the
popup a light weight menu.

4.2 Customizing Menu Layout
A JMenuBar by default is governed by a BoxLayout. The BoxLayout allows the user to customize the
menu bar by adding invisible components called glue components. By adding glue components, the user
can add extra spaces between menus or shift a menu to the extreme right of the menu bar. For example,

V 1.0 © Aptech Limited

Concepts

lightweight: If set to true popup becomes light weight popup menu, otherwise not.

Session

4
Menu Components

menus, such as Help or Exit can be placed at the extreme right.

4.2.1 Box Class
The Box class represents a lightweight container which uses a BoxLayout manager. The Box class provides
several useful methods that are useful for containers which are governed by BoxLayout Manager. The
Box class is used to create several types of invisible components, like glue, strut, and rigid-areas. This
invisible components can be used to change the effect of the component layout. The rigid-area is used to
specify fixed-size space between components in the layout.
Syntax:
public static Component createRigidArea(Dimension d)

where,
d: Is an object of the Dimension class.

To provide a horizontal space between the component, specify the required width, and set the height to
zero. To provide a vertical space between the component, specify the required height, and set the width
to zero.
The strut is also used to specify fixed-size space between components in the layout. Struts have unlimited
maximum height and width and hence, it is recommended to use rigid-area. Using struts one can make
the components too tall or wide.
Syntax:
public static Component createHorizontalStrut(int width)
public static Component createVerticalStrut(int height)

where,
width: Is an integer specifying the width of the invisible component, should be greater than zero.
height: Is an integer specifying the height of the invisible component, should be greater than

zero.

Component: Is the invisible component created to act as a strut.

Concepts

The glue is used to specify extra space between components in the layout. This extra space can be
stretched horizontally or vertically. The Box class has a static method createVerticalGlue() which
creates a vertical glue between components.
Syntax:
public static Component createVerticalGlue()
public static Component createHorizontalGlue()

The Box class has a static method createHorizontalGlue() which creates a horizontal glue between
components.

V 1.0 © Aptech Limited

4

Session

Menu Components

Code Snippet 9 shows how to use horizontal glue to provide a horizontal gap before the last menu.
Code Snippet 9:
// Import the necessary classes
import javax.swing.*;
import java.beans.*; // For property change listener interface and classes
import java.awt.*;
import java.io.File;
public class Demo2 {
public static void main(String[] args){
JFrame frm;
JMenuBar mnbBar;
JMenu mnuFile, mnuEdit, mnuView, mnuHelp;
mnbBar = new JMenuBar();
// Creates a frame
frm = new JFrame();
frm.setSize(400,400);
frm.add(mnbBar);
mnuFile = new JMenu(“File”);
mnuEdit = new JMenu(“Edit”);
mnuView = new JMenu(“View”);
mnuHelp = new JMenu(“Help”);
// Add the menus
mnbBar.add(mnuFile);
mnbBar.add(mnuEdit);
mnbBar.add(mnuView);
mnbBar.add(Box.createHorizontalGlue());
// Add the last menu
mnbBar.add(mnuHelp);
frm.setJMenuBar(mnbBar);
frm.setVisible(true);

V 1.0 © Aptech Limited

Concepts

// Add a Horizontal Glue

Session

4
Menu Components

}
}

4.2.2 Mixing Heavy and Light Components
As a general rule Swing components and Abstract Window Toolkit(AWT) components should not be
mixed in an application. A Java GUI application should be entirely Swing based or AWT based especially
when an application uses menu system.
A menu uses another component to implement the window which displays the menu items when
activated. Lightweight menus use component like JPanel whereas heavyweight menus may use Panel
or a subclass of Window which is heavyweight.
The lightweight popup windows are more efficient than their heavyweight counterparts. The lightweight
popup window do not work properly if the GUI application has heavyweight components whose display
area intersects with the lightweight component display area. This is because a heavyweight component
is always drawn on top. The lightweight popup window appears under the heavyweight component.
There is however a work around to solve this problem. The javax.swing.JPopupMenu provides a
static method setLightWeightPopupEnabled() which accepts a boolean value. By passing a value
false the popup window will use a heavyweight component.
Syntax:
JPopupMenu.setLightWeightPopupEnabled(false);

4.3 JFileChooser
A JFileChooser is a standard dialog box that is used to navigate the file system to choose a directory
or a file.

Concepts

A JFileChooser is used to:

Accept a directory or file name to create a new one.

Perform operations like open and save, with different labels and buttons.

Provide previews and display appropriate icons.

Display the files with required criteria by applying filters.

Note - Depending upon the operating system the JFileChooser dialog is displayed with a different
look and feel. Starting from JDK 1.4, a JFileChooser supports networking and allows choosing a

directory or file from a network.

V 1.0 © Aptech Limited

4

Session

Menu Components

4.3.1 Creating a JFileChooser
A file chooser can be created using any one of the following constructors:

JFileChooser()

The constructor constructs a JFileChooser instance pointing to the user’s default directory.
The statement to create the file chooser with the default directory. The statement JFileChooser
fcrChooser = new JFileChooser(); is used.

JFileChooser(String directoryPath)

The constructor constructs a JFileChooser instance with the specified path.
Syntax:
public JFileChooser(String directoryPath)

where,

directoryPath: Is the string representing the path of a valid directory. The statement
JFileChooser fcrChooser = new JFileChooser(“D:\Projects”); ������������
creates the
file chooser with the ‘D:\Projects’ as the directory path.

4.3.2 Methods of JFileChooser
The JFileChooser has following methods:

int showDialog(Component, String)

The method displays a custom dialog box having an approve button with the specified label.
Syntax:
public int showDialog(Component parent, String approveButtonLabel)

where,

parent: Pops up this dialog box, it can be null.
approveButtonLabel: is the label of the button.

JFileChooser.CANCEL _ OPTION if you cancel the dialog box.

JFileChooser.APPROVE _ OPTION if you accept the file.

JFileChooser.ERROR _ OPTION if an error occurs or the dialog is dismissed.

V 1.0 © Aptech Limited

Concepts

int: return type, can be one of the following valid values:

Session

4
Menu Components

The following statement shows how to display a file chooser dialog box with the button having the
label ‘Execute Application’:
int returnValue = fcrChooser.showDialog(this, “Execute Application”);

int showSaveDialog(Component)

The method displays a standard ‘Save File’ dialog box.
Syntax:
public int showSaveDialog(Component parent)

where,
parent: pops up this dialog box, it can be null.
int: return type can be one of the following valid values:
JFileChooser.CANCEL_OPTION,
JFileChooser.ERROR_OPTION.

JFileChooser.APPROVE_OPTION

and

The statement int returnValue = fcrChooser.showSaveDialog(this); displays a
standard ‘Save File’ dialog box.

int showOpenDialog(Component)

The method displays a standard ‘Open File’ dialog box.
Syntax:
public int showOpenDialog(Component parent)

where,

parent: pops up this dialog box, it can be null.
int: return type, can be one of the following valid values:
JFileChooser.CANCEL_OPTION, JFileChooser.APPROVE_OPTION, and
JFileChooser.ERROR_OPTION.

4.3.3 More Methods of JFileChooser
The JFileChooser has following methods:

Concepts

public File getSelectedFile()

The method returns an instance of the File representing the file selected from the dialog box.
Syntax:
public File getSelectedFile()

where,

File: is an instance of the File class representing the file selected from the dialog box.

V 1.0 © Aptech Limited

4

Session

Menu Components

Code Snippet 10 shows how to retrieve the file selected in the dialog box.
Code Snippet 10:
JFileChooser fcrChooser;
// Creates a file chooser
fcrChooser = new JFileChooser();
// Opens the standard “Open File” dialog box
int returnValue = fcrChooser.showOpenDialog(parent);
// Checks whether you have accepted the file
if (returnValue == JFileChooser.APPROVE_OPTION)
{
// Retrieve the file name
File file = fcrChooser.getSelectedFile();
}
else
{
System.out.println(“File not selected.”);
}

public File getCurrentDirectory()

The method returns an instance of the File representing the current directory.
Syntax:
public File getCurrentDirectory()

where,

File: Is an instance of the File class representing the current directory.

Code Snippet 11 shows how to retrieve the directory selected in the dialog box.
JFileChooser fcrChooser;
File currentDir;
// Creates a file chooser
fcrChooser = new JFileChooser();
// Retrieves the selected directory.
currentDir = fcrChooser.getCurrentDirectory();

V 1.0 © Aptech Limited

Concepts

Code Snippet 11:

Session

4
Menu Components

4.4 Need of Filter
The JFileChooser by default displays all the files in the current directory. However, at times it is
required to display only those files which match certain criteria.
For example:

Display all files with specified extensions.

Display only image files.
To meet this requirement you have to apply a filter to the JFileChooser so that only those files
which match the criteria are displayed.

Concepts

Figure 4.13 displays the Filter.

Figure 4.13: Filter

V 1.0 © Aptech Limited

4

Session

Menu Components

4.4.1 Creating Filters
Swing provides the javax.swing.filechooser.FileFilter class to create filters. The javax.
swing.filechooser.FileFilter is an abstract class with no default implementation. You have to
sub-class this abstract class and provide your own implementation to specify the filter criteria.
Code Snippet 12 shows how to create a filter which will display only directories and image files with
extension .gif, .jpg, and .png.
Code Snippet 12:
public class ImageFilter extends FileFilter {
// Method to decide the criteria
public boolean accept(File file) {
// If it is a directory it may contain image files so ignore it
if (file.isDirectory()) {
return true;
}
// Retrieves the file name.
String name = file.getName();
// Only accept images with extension of .gif,.jpg and .png
if (name.endsWith(“.gif”) || name.endsWith(“.jpg”) ||
name.endsWith(“.png”))
return true;
else
return false;
}
// Description of the filter
public String getDescription() {
return “Image files”;
}

Concepts

}

V 1.0 © Aptech Limited

Session

4
Menu Components

Figure 4.14 shows the output for Code Snippet 12.

Figure 4.14: Output - Filters
Note - When a subclass extends from an abstract class the sub-class inherits abstract methods

from the super class. The sub-class should provide the implementation (method definition) of all
abstract methods of its super class, failing which the sub-class will be abstract.

4.4.2 Setting Filter
Once you have an instance of the sub-class of javax.swing.filechooser.FileFilter class, you
typically set the filter using the setFileFilter() method of JFileChooser. The method takes
one argument, an object of any class which implements javax.swing.filechooser.FileFilter
interface.
Syntax:
public void setFileFilter(Filter filter)

where,
filter: Is an object of any class which implements javax.swing.filechooser.FileFilter

interface.

Code Snippet 13 how to set the filter.
Code Snippet 13:
// Create a file chooser
fcrChooser = new JFileChooser();
// Creates an object of class ImageFilter

Concepts

ImageFilter filter = new ImageFilter();
// Sets the filter
fcrChooser.setFileFilter(filter);

V 1.0 © Aptech Limited

4

Session

Menu Components

4.4.3 Customizing the File View
The JFileChooser class displays the list of directories and files with a small icon to represent a directory
and file. This view can be customized to represent different files with different icons to depict their
meaning better. For example, if the files in the directory are image files then different icons can be used
to represent extensions like jpeg, gif, png, and so on.
To create a customized file view, create a subclass of the FileView class. The javax.swing.
filechooser.FileView class is an abstract class with five methods which have to be implemented.
The abstract methods are:

getName()

getDescription()

getTypeDescription()

getIcon()

isTraversable()

4.4.4 getName() Method
The getName() method returns the file-name.
Syntax:
public String getName(File f)

where,
f: Is an object of the File class.
String: The return value is a String. A null String is returned if the Look and Feel should decide

the name of the file.

4.4.5 getDescription() Method
Syntax:
public String getDescription (File f)

where,
f: Is an object of the File class.

String: A string representing human readable description. A null is returned if the Look and Feel

should decide the name of the file.

V 1.0 © Aptech Limited

Concepts

The getDescription() method return a human readable description of the file name.

Session

4
Menu Components

4.4.6 getTypeDescription() Method
The getTypeDescription() method returns a human readable description of the file extension.
For example, for a file with extension ‘.png’, the user can return ‘A Portable Network Graphics Lossless
Compressed Image File’.
Syntax:
public String getTypeDescription (File f)

4.4.7 getTypeDescription() Method
The getTypeDescription() method returns a human readable description of the file extension.
For example, for a file with extension ‘.png’, the user can return ‘A Portable Network Graphics Lossless
Compressed Image File’.
Syntax:
public String getTypeDescription (File f)

where,
f: Is an object of the File class.
String: A string representing human readable description of the file extension.

4.4.8 getIcon() Method
The getIcon() method returns an icon representing a file in the JFileChooser.
Syntax:
public Icon getIcon (File f)

where,
f: Is an object of the File class.
Icon: An icon object created with the specified file name.

Concepts

4.4.9 isTraversable() Method
The isTraversable() method decides whether a directory is traversable. Most implementations of
this method should return null to indicate that the Look and Feel should decide it. It is normally used to
prevent users from descending into a certain type of directory representing a compound document. The
isTraversable() method should never return true for a non-directory.
A compound directory should not be descended or expanded to view the files and subdirectories.

V 1.0 © Aptech Limited

4

Session

Menu Components

Syntax:
public Boolean isTraversable (File f)

where,
f: Is an object of the File class,
Boolean: A true indicates that the directory is traversable.

Code Snippet 14 shows how to subclass the FileView class and use its methods.
Code Snippet 14:
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
public class ImageFileView extends FileView {
ImageIcon jpgIcon = new ImageIcon(“jpgIcon.gif”);
ImageIcon gifIcon = new ImageIcon(“gifIcon.gif”);
ImageIcon tiffIcon = new ImageIcon(“tiffIcon.gif”);
ImageIcon pngIcon = new ImageIcon(“pngIcon.png”);
public String getName(File f) {
return null; // let the Look and Feel(L&F) decide
}
public String getDescription(File f) {]
return null; // let the L&F of FileView figure this out
}
public Boolean isTraversable(File f) {
return null; // let the L&F FileView figure this out
}
public String getTypeDescription(File f) {

Concepts

String extension;
String type = null;

V 1.0 © Aptech Limited

Session

4
Menu Components

int dotPosition = f.getName().indexOf(“.”);
extension = f.getName().substring(dotPosition);
if (extension != null) {
if (extension.equals(“jpeg”) || extension.equals(“jpg”)) {
type = “JPEG Image”;
} else if (extension.equals(“.gif”)){
type = “GIF Image”;
} else if (extension.equals(“tiff”) || extension.equals(“tif”)) {
type = “TIFF Image”;
} else if (extension.equals(“png”)){
type = “PNG Image”;
}
}
return type;
}
public Icon getIcon(File f) {
String extension;
Icon icon = null;
int dotPosition = f.getName().indexOf(“.”);
extension = f.getName().substring(dotPosition);
if (extension != null) {
if (extension.equals(“jpeg”) || extension.equals(“jpg”)) {
icon = jpgIcon;
} else if (extension.equals(“gif”)) {
icon = gifIcon;

Concepts

} else if (extension.equals(“tiff”) || extension.equals(“tif”)) {
icon = tiffIcon;
} else if (extension.equals(“png”)) {
icon = pngIcon;
}
}

V 1.0 © Aptech Limited

4

Session

Menu Components

Code Snippet 15 shows how to set the ImageFileView instance.
Code Snippet 15:
JFileChooser fcrChooser = new JFileChooser();
fcrChooser.setFileView(new ImageFileView());

Figure 4.15 shows the output for Code Snippet 15.

Figure 4.15: Output - JFileChooser

4.5 JToolBar
A JToolBar is similar to a menu bar and contains buttons with icons. These buttons generate events
when clicked and can be associated with actions.
A JToolBar serves the same purpose as a JMenuBar, except that a JToolBar takes up less space with
an icon compared to a menu item on a menu bar. A JToolBar is dockable. You can click the JToolBar
and drag it to another location or any side of its parent container.

4.5.1 Dockable JToolBar
A dockable toolbar is also called as a floatable toolbar. A dockable toolbar can be moved around from
one part of Graphical User Interface to other by the user. A JToolBar is dockable only if the container it
belongs to has a BorderLayout layout manager. In order to keep a toolbar dockable and work properly
it is recommended that you add the JToolBar to any one side of a container. Do not add any component
to the remaining four sides.

Concepts

Figure 4.16 shows a dockable JToolBar.

Figure 4.16: Dockable JToolbar

V 1.0 © Aptech Limited

4

Session

Menu Components

4.5.2 Creating a ToolBar
A JToolBar can be created using any one of the following constructors:

JToolBar()

The constructor constructs a toolbar with the default horizontal orientation.
Code Snippet 16 shows how to create a toolbar with the default orientation and add it to a frame
in the north direction.
Code Snippet 16:
public class Display extends JFrame {
JToolBar tbrTools;
// Creates a toolbar
tbrTools = new JToolBar();
// Adds the toolbar to the frame in the north direction
getContentPane.add(tbrTools,BorderLayout.NORTH);
}

JToolBar(int orientation)

The constructor constructs a toolbar with the specified orientation.
Syntax:
public JToolBar(int orientation)

where,

orientation: Is used to set the orientation of the JToolBar. The valid values for orientation
are JToolBar.HORIZONTAL or JToolBar.VERTICAL

Code Snippet 17 shows how to create a toolbar with the vertical orientation and add it to a frame
in the north direction.
Code Snippet 17:

Concepts

public class Display extends JFrame
{
JToolBar tbrTools;
// Creates a toolbar with the vertical orientation
tbrTools = new JToolBar(JToolBar.VERTICAL);

V 1.0 © Aptech Limited

4

Session

Menu Components

// Adds the toolbar to the frame in the north direction
getContentPane.add(tbrTools,BorderLayout.NORTH);
}

JToolBar(String title)

The constructor constructs a toolbar with the specified title.
Syntax:
public JToolBar(String title)

where,

title: is a string to be displayed when the undocked toolbar is created.

Code Snippet 18 shows how to create a toolbar with the title ‘Palette’ and add it to a frame in the
north direction.
Code Snippet 18:
public class Display extends JFrame{
JToolBar tbrTools;
// Creates a toolbar with the title “Palette”
tbrTools = new JToolBar(“Palette”);
// Adds the toolbar to the frame in the north direction
getContentPane.add(tbrTools,BorderLayout.NORTH);
}

JToolBar(String title, int orientation)

The constructor constructs a toolbar with the specified title and orientation.
Syntax:
public JToolBar(String title, int orientation)
title: is a string to be displayed when the toolbar is created.
orientation: is used to set the orientation of the JToolBar. The valid values for orientation
are JToolBar.HORIZONTAL or JToolBar.VERTICAL.

V 1.0 © Aptech Limited

Concepts

where,

4

Session

Menu Components

Code Snippet 19 shows how to create a toolbar with the title ‘Palette’ and vertical orientation and
add it to a frame in the north direction.
Code Snippet 19:
public class Display extends JFrame{
JToolBar tbrTools;
// Creates a toolbar with the title “Palette” and vertical
// orientation
tbrTools = new JToolBar(“Palette”,JToolBar.VERTICAL);
// Adds the toolbar to the frame in the north direction
getContentPane.add(tbrTools,BorderLayout.NORTH);
}

4.5.3 Adding Buttons
To add a button with tooltip to JToolBar, you perform the following steps:

Declare an object of JButton class.

Instantiate the object with an ImageIcon.

Use the method setToolTipText() of JButton class to set a tool tip.

Use the add() method of JToolBar and pass the button instance as an argument.
Code Snippet 20 shows how to add the ‘Save’ button with the image icon to the container and set
its tool tip text.
Code Snippet 20:
JToolBar tbrTools;
JButton btnSave;
...

Concepts

...
// Creates a toolbar
tbrTools = new JToolBar();

V 1.0 © Aptech Limited

4

Session

Menu Components

// Adds the toolbar to the frame in the north direction
getContentPane().add(tbrTools,BorderLayout.NORTH);
...
// Creates a button with the icon
btnSave = new JButton(new ImageIcon(“Save.gif”));
// Sets the tool tip of the button “Save”
btnSave.setToolTipText(“Save”);
// Adds the button “Save” to the toolbar
tbrTools.add(btnSave);
...

4.5.4 Methods of JToolBar
The important methods of the JToolBar are as follows:

public Component add(Component component)

The method is used to add a button with an icon to the toolbar.
This method is actually derived from Container class, the base class of JToolBar.
Syntax:
public Component add(Component component)

where,

component: Is typically an object of the JButton class with an icon.
Component: Is an object of a component added to the tool bar.

Example: The statement tbrTools.add(btnsave); adds the JButton ‘Save’.

public void addSeparator()

The method adds a separator between buttons of a toolbar.

public void setBorderPainted(boolean paintBorder)

The method is used to paint a border around the toolbar.

V 1.0 © Aptech Limited

Concepts

Example: The statement tbrTools.addSeparator(); adds a separator between buttons of a
toolbar.

Session

4
Menu Components

Syntax:
public void setBorderPainted(boolean paintBorder)

where,

paintBorder: If set to true border is painted around the toolbar. By default, it is true.

Example: The statement tbrTools.setBorderPainted(true); paints a border around the
toolbar.

4.5.5 More Methods of JToolBar
The important methods of the JToolBar are as follows:

public void setFloatable(boolean floatable)

The method is used to make the toolbar dockable or non dockable.
Syntax:
public void setFloatable(boolean floatable)

where,

floatable: If set to true the toolbar can be moved, by default it is true.

Example: The statement tbrTools.setFloatable(true); makes the toolbar movable.

public void setOrientation(int orientation)

The method is used to change the orientation of the toolbar. The orientation can be either horizontal
or vertical.
Syntax:
public void setOrientation(int orientation)

where,

orientation: Is the orientation of the JToolBar to be set. The valid values for orientation
are JToolBar.HORIZONTAL or JToolBar.VERTICAL.

Concepts

Example: The statement tbrTools.setOrientation(JToolBar.HORIZONTAL); changes the
orientation of the toolbar to horizontal.

4.5.6 Customizing the Toolbar
The toolbar can be customized with the following features:

Make the edge of toolbar button invisible

Add a Separator

V 1.0 © Aptech Limited

4

Session

Menu Components

Add non-button components

4.5.7 Making the Edge of the Toolbar Buttons Invisible
The JToolBar has a method setRollover() which can be used to make the edges of the toolbar
buttons invisible, except for the toolbar button which is under the mouse pointer.
Syntax:
public void setRollover(boolean invisible)

where,
invisible: is a boolean, which specifies the visibility of the buttons edge. If true only the button

under the mouse pointer will have visible edge, if false all the buttons of the toolbar will have a
visible edge.
Code Snippet 21 shows how to make the edges of toolbar buttons invisible, except for the one under the
mouse pointer.
Code Snippet 21:
JToolBar tbrTool;
// Creates a toolbar
tbrTool = new JToolBar();
// Adds the toolbar to the frame in the north direction
getContentPane.add(tbrTool,BorderLayout.NORTH);
// Make the edge of buttons invisible, except the one under mouse pointer
tbrTool. setRollover(true);

4.5.8 Adding Separator
The JToolBar has a method addSeparator() which can be used to add a separator between buttons
of the toolbar.
Syntax:

Concepts

public void addSeparator ()

V 1.0 © Aptech Limited

Session

4
Menu Components

Code Snippet 22 shows how to add a separator between buttons of the toolbar.
Code Snippet 22:
public class Demo {
public static void main(String[] args){
JFrame frm;
JToolBar tbrTool;
JButton btnOpen, btnSave;
// Creates a frame
frm=new JFrame();
frm.setSize(400,400);
frm.setVisible(true);
// Creates a toolbar
tbrTool = new JToolBar();
// Adds the toolbar to the frame in the north direction
frm.add(tbrTool, BorderLayout.NORTH);
// Create the Open button
btnOpen = new JButton(new ImageIcon(“Open.gif”));
// Add the open button
tbrTool.add(btnOpen);
// Add a separator before the next button on the toolbar
tbrTool.addSeparator();
// Create the Save button
btnSave = new JButton(new ImageIcon(“Save.gif”));
// Add the open button
tbrTool.add(btnSave);

Concepts

}
}

V 1.0 © Aptech Limited

4

Session

Menu Components

4.5.9 Adding Non-Button Component to a Toolbar
The add() method of the JToolBar also allows to add a non-button component like a textfield to the
toolbar.
Code Snippet 23 shows how to add a non-button component to a toolbar.
Code Snippet 23:
// Import the necessary classes
import javax.swing.*;
import java.beans.*; // For property change listener interface and classes
import java.awt.*;
import java.io.File;
public class Demo1 {
public static void main(String[] args){
JToolBar tbrTool;
JButton btnOpen;
JTextField txfOpen;
JFrame frm;
// Creates a frame
frm=new JFrame();
frm.setSize(400,400);
frm.setVisible(true);
// Creates a toolbar
tbrTool = new JToolBar();
// Adds the toolbar to the frame in the north direction
frm.add(tbrTool, BorderLayout.NORTH);
// Create the Open button
btnOpen = new JButton(new ImageIcon(“Open.gif”));

Concepts

// Add the open button
tbrTool.add(btnOpen);

V 1.0 © Aptech Limited

Session

4
Menu Components

// Add a non-button component to the toolbar
txfOpen = new JTextField();
tbrTool.add(txfOpen);

Concepts

}

V 1.0 © Aptech Limited

4

Session

Menu Components

4.6 Check Your Progress
1.

Which of the statements about menu are true?
A.
B.
C.
D.
E.
(A)
(B)

2.

Each of the menu items displayed as choices in the menu drop down is associated with
actions to perform desired action.
The popup menu provided in GUI is invisible at first sight.
The menu bar contains items called menu items.
A menu system provides a bar above the window’s title bar called as menu bar.
A menu when clicked drops down to display various choices called menu items.
A, B, and D
C, D, and E

(C)
(D)

B, C, and D
A, B, and E

You are trying to create the check box menu item ‘Standard’ initially selected and another item ‘Auto
Text’ and add them to the ‘Toolbars’ menu item. Which of the options will help you to achieve
this?
A.

JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncAutoText;
mncStandard = new JCheckBoxMenuItem(“Standard”);
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);

B.

mniToolbars.add(mncStandard); mniToolbars.add(mncAutoText);
JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncAutoText;
mncStandard = new JCheckBoxMenuItem(“Standard”);
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);
add(mncStandard);

C.

add(mncAutoText);
JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncAutoText;
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);
mniToolbars = new JMenuItem();
mniToolbars.add(mncStandard);
mniToolbars.add(mncAutoText);

V 1.0 © Aptech Limited

Concepts

mncStandard = new JCheckBoxMenuItem(“Standard”, true);

Session

4
Menu Components
D.

JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncAutoText;
mncStandard = new JCheckBoxMenuItem(“Standard”, false);
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);
mniToolbars.add(mncStandard);
mniToolbars.add(mncAutoText);

3.

You are trying to create the popup menu with ‘Mark’, ‘Copy’ items in it. Which of the options will
help you to achieve this?
A. JPopUpMenu mnpPopup;
JMenuItem mniMark,mniCopy;
mnpPopup = new JPopUpMenu();
mniMark = new JMenuItem(“Mark”);
mnpPopup.add(mniMark);
mniCopy = new JMenuItem(“Copy”);

B.

mnpPopup.add(mniCopy);
JPopupMenu mnpPopup;
JMenuItem mniMark, mniCopy;
mnpPopup = new JPopupMenu();
mniMark = new JMenuItem(“Mark”);
mnpPopup.add(mniMark);
mniCopy = new JMenuItem(“Copy”);

C.

mnpPopup.add(mniCopy);
JPopupMenu mnpPopup;
JPopupMenuItem mniMark, mniCopy;
mnpPopup = new JPopupMenu();
mniMark = new JPopupMenuItem(“Mark”);

Concepts

mnpPopup.add(mniMark);
mniCopy = new JPopupMenuItem(“Copy”);
mnpPopup.add(mniCopy);

V 1.0 © Aptech Limited

4

Session

Menu Components

D. JPopupMenu mnpPopup;
JMenuItem mniMark, mniCopy;
mnpPopup = new JPopupMenu();
mniMark = new JMenuItem(“Mark”);
JPopupMenu.add(mniMark);
mniCopy = new JMenuItem(“Copy”);
JPopupMenu.add(mniCopy);

4.

Which of the statements about JFileChooser are true?
A. A JFileChooser does not allow to input a file name to create a new one.
B. A JFileChooser is a standard dialog box to navigate the file system to choose only
file.
C. The javax.swing.filechooser.FileFilter is an abstract class.
D. The JFileChooser dialog can be customized to provide previews and display
appropriate icons.
E. The JFileChooser by default displays all the files in the current directory.
(A)
(B)

5.

C, D, and E
B, D, and E

(C)
(D)

B, C, and D
A, C, and D

You are trying to create the file chooser with the ‘C:\Assignments’ as the directory path. Which
of the options will help you to achieve this?
A. JFilechooser fcrChooser;
B.

fcrChooser = new JFilechooser(“C:\Assignments”);
JFileChooser fcrChooser;

C.

fcrChooser = new JFileChooser(“C:\Assignments”);
JFileChooser fcrChooser;

D.

fcrChooser = new JFileChooser(“C:\Assignments”);
JFileChoose fcrChooser;
fcrChooser = new JFileChoose(“C://Assignments”);

Which of the statements about JToolBar are true?
A.
B.
C.
D.
E.

A JToolBar is similar to a menu and contains buttons with icons.
A dockable toolbar is also called as a floatable toolbar.
A JToolBar is dockable only if the container it belongs has a BorderLayout.
A JToolBar is dockable means you cannot drag it to another location.
A JToolBar serves the same purpose as a JMenuBar.

V 1.0 © Aptech Limited

Concepts

6.

Session

4
Menu Components
(A)
(B)

7.

B and C
C and D

(C)
(D)

B and E
A and C

Can you match the methods of JToolBar against their description?
Method

(A)
(B)
(C)
(D)
(E)

addSeparator()

(A)
(B)

A-4, B-1, C-5, D-2, E-3
A-2, B-3, C-1, D-5, E-4

setFloatable()
add()

setBorderPainted()

(C)
(D)

A-5, B-4, C-3, D-2, E-1
A-3, B-2, C-5, D-4, E-1

Concepts

setOrientation()

1.
2.
3.
4.
5.

Descriptions
Makes toolbar dockable.
Displays border around the toolbar.
Changes the orientation.
Adds separator between buttons.
Adds a button.

V 1.0 © Aptech Limited

4

Session

Menu Components

4.6.1 Answers
D
C
B
A
C
C
A

Concepts

1.
2.
3.
4.
5.
6.
7.

V 1.0 © Aptech Limited

Session

4
Menu Components

Summary
A GUI based application has to perform various tasks; all these tasks cannot be accommodated on
a single screen. This is solved by using Menu components.

A menu provides a space-saving way to let the user choose one of several options. Other
components with which the user can make a one-of-many choice include combo boxes, lists, radio
buttons, spinners, and toolbars.

A JFileChooser is a standard dialog box to navigate the file system to choose a Directory or a File.
A JFileChooser also allows you to input a directory or file name to create a new one.

A JFileChooser dialog box is customized to perform operations such as file open and save, with
different labels and buttons.

A JToolBar is similar to a menu bar and contains buttons with icons. These buttons generate events
when clicked and can be associated with actions.

A JToolBar serves the same purpose as a JMenuBar. A JToolBar takes up less space with an icon
compared to a menu item on a menu bar.

The JToolBar can be customized by making the edge of the toolbar button invisible, adding
separator and adding non-button components.

Concepts

V 1.0 © Aptech Limited

Session 5
Lists and Panes
Welcome to the Session, Lists and Panes.
This session explains the JColorChooser control to choose a color through
a standard dialog box. The session also discusses list components to select
one or more items using a list and drop-down control. Further, the session
also discusses on how to optimize space usage in GUI applications using
tabbed and split panes. Finally, the session explains the layered pane that
is used to position components one over the other.
In this Session, you will learn to:
 Explain JColorChooser, its use, and how to create it
 List and explain methods and event handling for
JColorChooser
 Explain JList, its use, and how to create it
 List and explain methods and event handling for JList
 Explain JComboBox, its use, and how to create it
 List and explain methods and event handing of JComboBox
 Explain JSplitPane, its use, and how to create it
 Explain how to add, configure, and display a JSplitPane
 Explain JTabbedPane, its use and how to create it
 Explain how to add and display a JTabbedPane
 Explain event handling for JSplitPane and JTabbedPane

5

Session

Lists and Panes

5.1 Introduction
The JColorChooser has a control panel which allows the user to manipulate color. There are three
levels of API in the JColorChooser class:

A static convenience method which displays a modal dialog and returns the color selected.

A static method for creating a dialog with ActionListener that is invoked to set the color.

Directly creating instances of JColorChooser class within a container.

5.1.1 JColorChooser
JColorChooser is a class which creates a component allowing you to choose a color or a shade
dynamically. The JColorChooser provides three tabs to choose a color.

Table 5.1 lists the JColorChooser tabs.

Tab
Swatches
HSB
RGB

Description
To select a color from a collection of swatches.
By specifying the Hue, Saturation, and
Brightness.
By specifying the Red, Green, and Blue values.
Table 5.1: JColorChooser Tabs

A JColorChooser can be created using any one of the constructor methods listed in table 5.2.

Constructor

public
JColorChooser()

Description
Creates a JColorChooser with the
initial color as white.

Example

/* Creates a
JColorChooser
instance using
default constructor
*/
JColorChooser
ccrColors;

ccrColors = new
JColorChooser();

V 1.0 © Aptech Limited

Concepts

// Creates a
colorchooser

Session

5
Lists and Panes

Constructor

Description

public ColorChoo Creates a JColorChooser with the
ser(Colorinitial specified initial color.
Color)

Example

/* creates a
JColorChooser
instance with
parameterized
constructor */
JColorChooser
ccrColors;
Color crBlue;

/* Create a bluish
shade color with red
value = 31, green
value = 217, and blue
value = 237 */
crBlue = new
Color(31,217,237);
/* Create a
colorchooser with
the blue color */
ccrColors = new
lorChooser(crBlue);

Table 5.2: Constructor Methods of JColorChooser

5.1.2 Displaying JColorChooser

Concepts

Typically, the JColorChooser is used as a standard dialog box to choose the color. The java.awt
package has a class Color to create objects representing colors and their shades. The class Color has
constants to represent several known colors such as Color.red, Color.yellow, and so on. These
constants belong to the class Color.
The Color class also has several constructors to create different shades of color. The most commonly
used constructor is:
public Color(int red, int green, int blue)

This constructor creates a shade of color according to the integer values passed as arguments. These
values are treated as the red, green, and blue components.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Syntax:
public Color(int red, int green, int blue)

where,
red: Is an integer with a range 0 to 255 and represents the red component.
green: Is an integer with a range 0 to 255 and represents the green component.
blue: Is an integer with a range 0 to 255 and represents the blue component.

Consider the following statement:
Color clr = new Color(25,135,200);

Here, the statement creates a bluish shade as the blue component is greater than the red and green.

5.1.3 Adding JColorChooser
A JColorChooser can also be added as a component. It is added to the container using add() method
of the container which takes an object of the JColorChooser class as an argument. However, adding
JColorChooser as a component occupies more space.
Code Snippet 1 shows how to add the JColorChooser as a component to the frame.
Code Snippet 1:
JFrame mColorChooser;
JColorChooser ccrChoser;
// Creates a frame with the title “Color Chooser”
frmColorChooser = new JFrame(“Color Chooser”);
// Creates a color chooser
ccrChoser = new JColorChooser();
// Adds the color chooser to the frame

Concepts

frmColorChooser.getContentPane().add(ccrChoser);

V 1.0 © Aptech Limited

Session

5
Lists and Panes

Figure 5.1 shows the output for Code Snippet 1.

Figure 5.1: Output - JColorChooser

5.1.4 Event Handling
Concepts

To handle the events of JColorChooser, perform the following steps:

Retrieve ColorSelectionModel

The JColorChooser has a method getSelectionModel() which returns an object of the
ColorSelectionModel interface. The ColorSelectionModel represents a model which
supports selection of a color.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Syntax:
public ColorSelectionModel getSelectionModel()

where,

ColorSelectionModel: Is the return type representing the object reference of the
ColorSelectionModel.

Code Snippet 2 shows how to retrieve the ColorSelectionModel of a JColorChooser.
Code Snippet 2:
// Declares the chooser and model JColorChooser ccrChoser;
ColorSelectionModel colorSelectionModel;
// Retrieves the color selection model colorSelectionModel = crChoser.
getSelectionModel();

Register a ChangeListener object

The addChangeListener() method is used to register a javax.swing.event.
ChangeListener interface object with the ColorSelectionModel to handle the event of
selecting a color.
Syntax:
public void addChangeListener(ChangeListener listener)

where,

Listener: Is an object of the interface javax.swing.event.ChangeListener.

Code Snippet 3 shows how to register a ChangeListener with the ColorSelectionModel.
Code Snippet 3:
// Register a change listener with the selection model
colorSelectionModel.addChangeListener(new ChangeListener() {
...
});
Handle the event in stateChanged() method

The ChangeListener interface has a method stateChanged() which is invoked, when you
select a color. You provide the action code in this method.
Syntax:
public void stateChanged(ChangeEvent e)

where,

V 1.0 © Aptech Limited

Concepts

Session

5
Lists and Panes
e: Is an object of the ChangeEvent class.

Code Snippet 4 shows how to handle the color selection event and change the background color
of a label.
Code Snippet 4:
// Declares a chooser and a label JLabel lblMessage;
// Create and add the ccrChoser and lblMessage
...
// Retrieve the color selection model
colorSelectionModel = ccrChoser.getSelectionModel();
// Adds a change listener to the color selection model colorSelectionModel.
addChangeListener(new ChangeListener() {
Pu public void stateChanged(ChangeEvent e) {
Color clr = ccrChoser.getColor();
lblMessage.setBackground(clr);
}
});

Concepts

Figure 5.2 shows the output for Code Snippet 4.

Figure 5.2: Output – JColorChooser Event
V 1.0 © Aptech Limited

5

Session

Lists and Panes

5.1.5 Methods of JColorChooser
The important methods of JColorChooser are listed in table 5.3.

Method

C o l o
getColor()

Description

Example

r The method returns the currently selected JColorChooser
ccrChooser;
color.
Syntax:

Color clrColor;

public Color getColor()

// Creates a color
chooser
ccrChooser = new

where,

JColorChooser();

Color: Returns an object of class Color // Retrieves the
representing the currently selected color.
current

// color selected
clrColor =

void setColor
(Color)

ccrChooser.
getColor();
The method sets the specified color to be the // Set blue as the
current color
current color.
Syntax:
public void setColor(Color color)

JColorChooser
ccrChooser;
// Creates a color
chooser
ccrChooser = new

where,

color: is an object of class Color representing JColorChooser();

the color to be set.

// Sets blue as the
// current color
ccrChooser.setColor

Concepts

(Color.blue);

V 1.0 © Aptech Limited

Session

5
Lists and Panes

Method

Description

ColorshowDial The method displays the standard color
og(Component, dialog box.
String, Color)
Syntax:
public static Color
showDialog(Component parent,
String title, Color initialColor)

where,
parent: Is the top-level container to which

this dialog box belongs.

Example

/* Displays the
standard
color dialog box with
the title ‘Choose a
Color’ with red color
selected initially.
*/
Color clrColor =
JColorChooser.
owDialog(null,”Choose
a Color”, Color.red);

title: Is a string displayed as the title of the

dialog box.

initialColor: Is an object of the Color

class.

Table 5.3: Methods of JColorChooser

5.2 JList

Concepts

JList is a class used to displays a group of items. It allows you to choose one or more items. The items
in a JList can be displayed in one or more columns. A JList does not support scrolling inherently, a
JScrollPane is used to provide the scrolling functionality.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Figure 5.3 displays a JList.

Figure 5.3: JList

5.2.1 Constructing a JList
A JList can be created using any one of the following constructors listed in table 5.4.

Constructor

public JList()

public
items

Description
Creates an empty list.

Example

// Creates an empty
list

JList lstCountries =
new JList();
JList(Object[] Creates a list initialized with the items /* Create and
initialize the string
from the Object array.
array with the names
Syntax:
of countries */
String[]
strCountries =
where,
{“Australia”,
items: Is an array of objects containing “Belgium”, “Canada”,
. . . . “India”};
the items to be displayed in the list.
...
// Creates a list with
a string array
JList lstCountries =

V 1.0 © Aptech Limited

Concepts

public JList(Object[] items)

Session

5
Lists and Panes

Constructor

Description

public
JList(Vector Creates a list initialized with items
vecItems)
from a vector.
Syntax:
public JList(Vector
vecItems)

Example

=new
List(strCountries);
/* Create a list
with a Vector */
JList
lstCountries
=
new
List(vecCountries);

where,
vecItems: Is a Vector containing

the items to be displayed in the list.
Table 5.4: Constructors of JList
Code Snippet 5 shows how to create a list with a Vector representing names of the countries.
Code Snippet 5:
// Creates a vector to store the names of the countries Vector vecCountries = new
vector();
// Adds the names of the countries to the vector
vecCountries.addElement(“Australia”);
vecCountries.addElement(“Belgium”);
vecCountries.addElement(“Canada”);
...
vecCountries.addElement(“India”);
...
// Creates a list with a Vector

Concepts

JList lstCountries = new JList(vecCountries);

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Figure 5.4 shows the output for Code Snippet 5.

Figure 5.4: Output of JList

5.2.2

Configuring and Displaying JList

To add a JList, perform the following steps:

Create an instance of JList.

Create an instance of JScrollPane and pass the list instance as an argument.

Add the JScrollPane instance to a container.

Code Snippet 6 shows how to add the list to the panel.
Code Snippet 6:
JPanel pnlCountries;
JList lstCountries;
String[] strCountries;
...
// Creates string array and initialize it with countries name
String[] strCountries = {“Australia”, “Belgium”, “Canada”,. . . “India”};
// Creates a list with the string array

V 1.0 © Aptech Limited

Concepts

JScrollPane scpScroller;

Session

5
Lists and Panes

lstCountries = new JList(strCountries);
// Provides the list to the scrollpane to facilitate scrolling scpScroller = new
ScrollPane(lstCountries);
// Adds the JScrollPane to the panel pnlCountries.add(scpScroller);

Figure 5.5 shows the output for Code Snippet 6.

Figure 5.5: Output – JLIst in Panel

5.2.3 Methods of JList
To display a JList, no special step is required, when a JScrollPane is initialized with a JList instance,
it is displayed by default.
Methods of JList are as follows:

Configuring JList

To configure a JList, invoke the methods listed in table 5.5.

Method

Concepts

public void
SelectionMode(int
selectMode)

Description

Example

This method sets the selection
mode for the list, where
selection mode determines how
the items are selected. Items
are selected as single, multiple
selections contiguously, or in
any order.
selectMode: Is one of the

predefined values
selection mode.

V 1.0 © Aptech Limited

of

the

/*
Sets
the
single
selection mode in the
list */
JList lstCountries;
. . .

5

Session

Lists and Panes

Method

Description
SINGLE_SELECTION:

Example

Allows lstCountries.

selecting of a single item.

setSelectionMode

SINGLE_INTERVAL_ ( J L i s t . S I N G L E _
SELECTION: Allows selecting SELECTION);

contiguous item.

MULTIPLE_INTERVAL_
SELECTION: Allows selecting
public void
setLayoutOrientation(int
layoutOrient)

items in any order, this is the
default mode.
This method sets the layout of This method sets the layout of
the cells in the list.
the cells in the list.
layoutOrient:

Is one of layoutOrient: Is one of
the predefined values of the predefined values of
orientation.
orientation.
JList.VERTICAL:

columns
vertically.

are

The JList.VERTICAL: The
displayed columns are displayed
vertically.

JList.HORIZONTAL_WRAP : JList.HORIZONTAL_WRAP:

The columns are displayed The columns are displayed
horizontally, they wrap to a new horizontally, they wrap to a
row if width is less.
new row if width is less.
JList.VERTICAL_WRAP: The JList.VERTICAL_WRAP:

columns are displayed vertically, The columns are displayed
they wrap to a new column if vertically, they wrap to a new
height is less.
column if height is less.
public void
setVisibleRowCount(int
count)

This method sets the number of /* Display four rows
rows to be displayed in the list in the list without
scrollbars */
without scrollbars.
JList lstCountries;
int count = 4;
lstCountries.
setVisibleRowCount
(count);

Table 5.5: Methods to Configure JList

V 1.0 © Aptech Limited

Concepts

. . .

Session

5
Lists and Panes

Getting Data from JList

Some of the methods to get data from JList are listed in table 5.6.

Method

public void
clearSelection()
public int

getSelected
Index()
public int[]getSel
ectedIndices()

public boolean
isSelectionEmpty()
public Color
getSelect
ionBackground()

Description

Example

This method is used to clear the
selection of the items from the list.
This method returns index of the
selected item as an integer value.
The index is zero-based.

lstCountries.
clearSelection();

This method returns an array of
indices of selected items. The array
containing the indices of multiple
items selected.
This method returns true if no
item is selected.

int[] indices =
lstCountries.
electedIndices();

This method returns the background
color of the selected item, which is
represented by the instance of the
Color class.

JList lstCountries;

int index = lstCountries.
tSelectedIndex();

boolean selected
= lstCountries.
isSelectionEmpty();

String[] strCountries
= {“Australia”,
“Belgium”, “Canada”, . .
. . “India”};
lstCountries =
new JList
(strCountries);
/* Retrieve the
background color
of selection
Color */

Concepts

clrBackground =
lstCountries.
getSelection
Background();

Table 5.6: JList

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Setting Data and Selecting Item

The important methods to set data in JList are listed in table 5.7.

Method

Description

public
void
setSelectedIndices(int[]
indices)
public void setSelectionBackgr
ound(Color c)

This method is used to select multiple items
programmatically.

public void setListData(Object[] This method is used to provide the JList
items)
with items as an array of Object or Vector.
public void setSelectedIndex(int This method is used to select a single item
index)
programmatically.

This method sets the background color of the selected
item.
public boolean isSelected(int This method is used to check if the item at the specified
index)
index is selected.
public void setSelectionForegr This method is used to set the foreground color of the
ound(Color c)
selected item from the list.
Example: lstCountries.setSelectionForegrou
nd(Color.red);

Here, the statement sets the foreground color of
selection to red.
Table 5.7: Methods in JList
Code Snippet 7 shows how to provide the list with items and select the items in the list
programmatically.
Code Snippet 7:
String[] strCountries;
JList lstCountries;
// Creates a string array with 20 elements

// Initialize the array with names of countries.
...
// Sets the items in the list
lstCountries.setListData(strCountries);

V 1.0 © Aptech Limited

Concepts

strCountries = new String[20];

Session

5
Lists and Panes

// Selects the third item in the list programmatically
lstCountries.setSelectedIndex(3);
// Creates an integer array with the two elements
int[] indices = new int[2];
indices[0] = 2;
indices[1] = 3;
// Set the items selected lstCountries.setSelectedIndex(indices);
for (int i = 0; i < 2 ; i++)
{
System.out.println(“Element” + i + from Indices array is” + indices[i]);
}

Figure 5.6 shows the output for Code Snippet 7.

Concepts

Figure 5.6: Output - Code Snippet 7

5.2.4 Event Handling
To handle the events of a JList, perform the steps listed in table 5.8.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Step

Register a
ListSelectionListener

Description
To handle the events of a JList, you register a
ListSelectionListener.
The ListSelectionListener is available in javax.
swing.event package.
The JList has a method addListSelectionListener()
to register a selection listener. The object of the
ListSelectionListener interface is passed as an
argument to this method.
Syntax:
Public void addListSelectionListener(ListSel
ectionListener e)

where,
e: Is an object of any class which implements
ListSelectionListener interface.

Add the action code in Whenever the value of a selection changes, the method
valueChanged () method valueChanged()of ListSelectionListener is
invoked. You add the code to handle the event in the
method valueChanged().
Table 5.8: Event Handling of JList
Code Snippet 8 demonstrates the code to register the list selection listener and add the valueChanged
() method.
Code Snippet 8:
JList lstCountries;
...
lstCountries.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{

Concepts

// Adds the action code
...
}
});

V 1.0 © Aptech Limited

Session

5
Lists and Panes

5.3 JComboBox
A JComboBox is a combination of a drop-down and a TextField. The drop-down displays one or more
items to choose from. The TextField allows you to type a new item not available in the drop-down.
A JComboBox occupies less space and yet allows you to choose one of several items from a list. A
JComboBox allows you to select only one item unlike a JList which allows multiple selections.

5.3.1 Constructing a JComboBox
A JComboBox can be created using one of the constructors listed in table 5.9.

Constructor

public JComboBox()

Description

Example

JComboBox cboFonts = new
JComboBox();
public JComboBox(Object[] Creates a combo box with the /* Create and initialize
items)
items contained in the Object a string array with 10
elements*/
array.

Creates an empty combo box.

String[] strFonts =
{“Arial”, ”Times New
Roman”,. . . . ”Verdana”};
/* Create a combo box with
the items from string array
*/

Concepts

JComboBox cboFonts = new
JComboBox(strFonts);

V 1.0 © Aptech Limited

5

Session

Lists and Panes

public JComboBox(Vector
items)

Creates a combo box with the /* Creates a vector to
store the font names Vector
items contained in the vector.
*/

vecFonts = new Vector();
/* Initializes the vector
with the font names */
vecFonts.
addElement(“Arial”);
vecFonts.
addElement(”Times New
Roman”);
....
vecFonts.
addElement(”Verdana”);
/* Creates a combo box
with the items from vector
JComboBox */
cboFonts = new
JComboBox(vecFonts);

Table 5.9: Constructors of JComboBox

Figure 5.7: JComboBox

5.3.2 Configuring and Displaying a JComboBox
To add a JComboBox, perform the following steps:

Create an instance of JComboBox.

V 1.0 © Aptech Limited

Concepts

Figure 5.7 shows a JComboBox with the list of items.

Session

5
Lists and Panes

Add it to the container using add() method.

The JComboBox component is displayed, when it is added to a container. The JComboBox is configured
using setEditable (boolean editable). This method sets the editable property to allow inputting
of text. If editable is set to true, you can input text in the combo box. By default, it is set to false.
Code Snippet 9 shows how to add the combo box to the panel and enable the input of the text.
Code Snippet 9:
// Creates a panel
JPanel pnlFonts = new JPanel();
// Creates a string array with 10 elements
String[] strFonts = new String[10];
// Initializes the array with font names
...
// Creates a combo box with the items from string array JComboBox cboFonts
new JComboBox(strFonts);
// Enables the inputting of text cboFonts.setEditable(true);

Concepts

// Adds the combo box to the panel pnlFonts.add(cboFonts);

V 1.0 © Aptech Limited

=

5

Session

Lists and Panes

Figure 5.8 shows the output for Code snippet 9.

Figure 5.8: Output - Adding Combo Box to Panel

5.3.3

Event Handling Using Action Listeners

The events of a JComboBox can be handled by ActionListener or ItemListener. To handle the
events by an ActionListener, you perform the steps listed in table 5.10.

Step

Description

Register ActionListener The addActionListener() method is used to
register an ActionListener object. This method

takes one argument, an object of a class which
implements the ActionListener interface.
Syntax:

where,

Add the action code in

actionPerformed()

method

e: Is an object of any class which implements the
ActionListener interface.

Whenever the item in the combo box is selected,
the actionPerformed() method is invoked, you
add the action code in this method

V 1.0 © Aptech Limited

Concepts

public void addActionListener(ActionL
istener e)

Session

5
Lists and Panes

Step

Description
Syntax:
public void actionPerformed(ActionEv
ent e)

where,
e: Is an object of the ActionEvent class.

Table 5.10: Event Handling for JComboBox
Code Snippet 10 shows how to register ActionListener to the font’s combo box and handle the event
performed on it.
Code Snippet 10:
JComboBox cboFonts;
...
// Registers the ActionListener cboFonts.addActionListener(new
ActionListener() {
// Handles the action performed event
public void actionPerformed(ActionEvent e) {
// Add the code to handle the event
}
});

5.3.4 Event Handling Using Item Listeners
To handle the events by an ItemListener, perform the following steps listed in table 5.11.

Step

Description

Register a ItemListener The addItemListener() method is used to register
an ItemListener event handler. This method takes an
argument of the ItemListener interface.

Concepts

Syntax:
public void addItemListener(ItemListener e)

where,
e: Is an object of the ItemListener interface.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Step

Description

Add the action code in Whenever you select an item from the combo box,
itemStateChanged() the itemStateChanged() method of ItemListener is
method
invoked. You add the action code in this method. The
itemStateChanged() gets an object of ItemEvent class.
This object has a method getStateChange() which returns
an integer. The returned value can be equated with the
constants ItemEvent.SELECTED or ItemEvent.DESELECTED.
Syntax:
public void itemStateChanged(ItemEvent e)

where,
e: is an object of the ItemEvent class.

Table 5.11: Event Handling Using ItemListener
Code Snippet 11 shows how to register the ItemListener event handler to the font’s combo box and
handle the item’s selected and deselected events on it.
Code Snippet 11:
JComboBox cboFonts = new JComboBox(strFonts);
...
// Register the ItemListener
cboFonts.addItemListener(new ItemListener()
{
// Handle the item state changed event
public void itemStateChanged(ItemEvent e)
{
// Check if it a Select or Deselect event
if (e.getStateChange() == ItemEvent.SELECTED)
{

Concepts

// SELECT event
...
} else
{
// DESELECT event

V 1.0 © Aptech Limited

Session

5
Lists and Panes

. ..
}
});
}

5.3.5

Methods of JComboBox

The important methods of a JComboBox are listed in table 5.12.

Method

public void addItem(Object item)

Description
The method is used to add an item to the
JComboBox only if the JComboBox is created with
the default constructor.
Example: cboFonts.addItem(“Times
Roman”);

public int getItemCount()

New

The method returns the number of items in the
JComboBox.
Example: int count = cboFonts.

public int getSelectedIndex()

getItemCount();

The method returns an integer representing the
index of the item selected.
Example: int

public Object getSelectedItem()

index
getSelectedIndex();

=

cboFonts.

The method returns an object representing the
item selected. The returned object is typically cast
to the appropriate class. If none of the items is
selected, null is returned.
Example: String item = (String) cbo.
getSelectedItem();

Concepts

public
void
editable)
public
index)

void

setEditable(boolean This method is used to make the JComboBox

editable.

Example: cboFonts.setEditable(true);
setSelectedIndex(int This method is used to select an item
programmatically.
Example: cboFonts.setSelectedIndex(2);

V 1.0 © Aptech Limited

5

Session

public
item)

Lists and Panes

void

Method

setSelectedItem(Object This

Description

method is used to select an item
programmatically. The object to be selected from
the list of items available is specified.
Example:

public Object getItemAt(int index)

cboFonts.
setSelectedItem(“Times New Roman”);

The getItemAt() method of JComboBox is used
to retrieve the item at the specified index.
/* Creates and initialize a string
array with 10 elements */
String[] strFonts = {“Arial”, ”Times
New Roman”,. . . . ”Verdana”};
/* Creates a combo box with the items
from string array */
JComboBox
cboFonts
JComboBox(strFonts);

=

new

// Retrieve the item at index 1

public int getMaximumRowCount()

String strFontName = (String)cboFonts.
getItemAt(1);

The getMaximunRowCount() method of
JComboBox is used to retrieve the maximum
number of items the combo box can display
without a scrollbar.
Example: The code to retrieve the maximum
row count.

/* Create and initialize
array with 10 elements */

a

string

String[] strFonts = {“Arial”, ”Times
New Roman”,. . . . ”Verdana”};
/* Create a combo box with the items
from string array */
=

new

/* Retrieve the maximum number of row
count */
int
rowCount
=
getMaximumRowCount();

V 1.0 © Aptech Limited

cboFonts.

Concepts

JComboBox
cboFonts
JComboBox(strFonts);

Session

5
Lists and Panes

Method

Description

public Object[]
getSelectedObjects()

The

getSelectedObjects() method of
JComboBox is used to retrieve multiple items

selected.

Example:
String[]
strNames
=
(String[])
cboFonts. getSelectedObjects();

public
void
insertItemAt(Object The insertItemAt() method of JComboBox is
item, int index)
used to insert an item at the specified index.

Example: The code to insert an item at the specified
index is as follows:
/* Create and initialize a string
array with 10 elements*/
String[] strFonts = {“Arial”, ”Times
New Roman”,. . . . ”Verdana”};
// Create a combo box with the items
from string array
JComboBox cboFonts = new
JComboBox(strFonts);
// Insert the new item at position 1
String strNewName = “Courier New”;
public void removeAllItems()

cboFonts.insertItemAt(strNewName,1);

The removeAllItems() method of JComboBox
is used to remove all items from the JComboBox.

Example: cboFonts.removeAllItems();
public void removeItemAt(int index) The removeItemAt() method of JComboBox is
used to remove the item at specified position from
the JComboBox.
Example: cboFonts.removeItemAt(1);

Concepts

Table 5.12: Methods of JComboBox

5.4 JTabbedPane
A JTabbedPane is a component which allows you to add several components usually panels, to share
the same space. Each component added to JTabbedPane has a tab, which can have a textual label or
an icon.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

You click the tab to choose the component to view. When a tab is clicked, its associated component
becomes current and is visible.
The main advantage of using a JTabbedPane is that several panels can be clubbed together to occupy
the same space in the GUI. It is very convenient to choose the panel based on the tab and to work in a
seamless manner.
Figure 5.9 displays the JTabbedPane.

Figure 5.9: JTabbedPane

5.4.1

Constructing a JTabbedPane

A JTabbedPane is created using any one of the constructors listed in table 5.13.
public JTabbedPane()

Description

Example

Creates an empty JTabbedPane JTabbedPane
with the default tab placement tpnProperties;
on top.
tpnProperties = new

JTabbedPane();
public
JTabbedPane(int Creates an empty JTabbedPane JTabbedPane
placement)
with the specified placement in tpnProperties;

the top or bottom or left or right tpnProperties = new
direction.
JTabbedPane(JTabbedPane.
BOTTOM);

V 1.0 © Aptech Limited

Concepts

Constructor

Session

5
Lists and Panes

Constructor

Description

Example

The placement argument is
having one of the following valid
values:
JTabbedPane.TOP,
JTabbedPane.BOTTOM,
JTabbedPane.LEFT,
JTabbedPane.RIGHT

Table 5.13: Constructors of JTabbedPane

5.4.2 Adding Tabs to JTabbedPane
To add tabs to a JTabbedPane, perform the following steps:

Create an instance of JTabbedPane.

Create an instance of a JPanel for each tab.

Add the components in the respective panels.

Use the addTab() method of JTabbedPane to add the panel.

To display the JTabbedPane, simply add it to the container.
The various addTab() methods of JTabbedPane are listed in table 5.14.

Method

void addTab(String title, Component
component)

Concepts

void addTab(String title, Icon icon,
Component component)
void addTab(String title, Icon icon,
Component component, String tip)

Description
The method adds a component with the specified
title. The argument title is a string specifying
the title of the tab. The argument component is
the component to be displayed.
The method adds a component with the specified
title and icon. The argument icon specifies an
image.
The method adds a component with the specified
title, icon, and the tool tip.

Table 5.14: Methods of JTabbedPane

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Figure 5.10 displays adding tabs to a JTabbedPane.

Figure 5.10: Adding Tabs to JTabbedPane
Code Snippet 12 shows how to add a panel with the title ‘English’, icon, and tooltip to the tabbed pane
and add the tabbed pane to the frame.
Code Snippet 12:
JFrame
frmSubjects; JPanel pnlEnglish; JTabbedPane tpnSubjects;
...
// Creates a frame with the title “Subjects”
frmSubjects = new

JFrame(“Subjects”);

// Create an image icon
ImageIcon iconEnglish = new ImageIcon(“English.gif”);
tpnSubjects.addTab(“English”,iconEnglish,pnlEnglish, “English Subject”);
// Adds the tabbedpane to the frame
frmSubjects.getContentPane().add(tpnSubjects);

V 1.0 © Aptech Limited

Concepts

// Adds panel having the title “English”, icon and tooltip to tabbedpane

Session

5

5.4.3

Lists and Panes

Event Handling

Generally, events generated by the JTabbedPane are consumed by the pane itself. Whenever you click a
tab to switch between the panes, a state changed event is generated. You register an object of the javax.
swing.event.ChangeListener interface to handle this event. To handle the change event, perform the
steps listed in table 5.15.

Step

Description

Register a ChangeListener

The addChangeListener() method is used to
register an object of the class which implements
the ChangeListener interface.
Example:
JTabbedPane tpnSubjects;
...
tpnSubjects.addChangeListener(new
ChangeListener() {. . .});

Add a stateChanged() method

The stateChanged() method of ChangeListener
interface is invoked, when you click the tabs to
switch through the panes.
Syntax:

public void stateChanged(ChangeEvent e)
where,
e: Is an object of the ChangeEvent class.

Table 5.15: Steps for Event Handling JTabbedPane
Code Snippet 13 shows how to handle state change event of the tabbed pane.
Code Snippet 13:
JTabbedPane tpnSubjects;

Concepts

...
// Register the ChangeListener tpnSubjects.addChangeListener(new
ChangeListener() {
// Handle the state changed event
public void stateChanged(ChangeEvent e) {
// Add the action code
...

V 1.0 © Aptech Limited

5

Session

Lists and Panes

}
});

5.5 JSplitPane
A JSplitPane is a component which displays two components and a divider. These two components
can be displayed horizontally (side by side) or vertically (one below the other). The divider can be dragged
to specify how much of the total area is to be given to each component. Two small arrows appear at the
top of the divider. These arrows allow you to collapse (and then expand) either of the components with
a single click.
The main advantage of JSplitPane is the ability to dynamically change the sizing requirements per
component basis. Examples of using JSplitPane are explorer in MS Windows operating system,
mailbox, and so on.
Figure 5.11 displays the JSplitPane.

Figure 5.11: JSplitPane
Note: If the two components are larger in size than the JSplitPane, then a JScrollPane is used to
facilitate scrolling. Only two components can be added to a JSplitPane. However, JSplitPane can

be nested. You can add a split pane as one of the components to another split pane.

JSplitPane()

Constructor

JSplitPane(int)

Description
The method creates a JSplitPane with the
components placed side by side with no continuous
layout.
The method creates a JSplitPane with the
specified orientation and no continuous layout.

V 1.0 © Aptech Limited

Concepts

A JSplitPane is created using any one of the constructors listed in table 5.16.

Session

5
Lists and Panes

Constructor

Description

JSplitPane(int, boolean)

The method creates a JSplitPane with the
specified orientation and continuous layout if the
second parameter is set to true.
The method creates a JSplitPane with the
specified orientation and continuous layout if
the second parameter is set to true. The two
components are placed either side by side or one
below the other.

JSplitPane(int, boolean)

Table 5.16: Constructors of JSplitPane
Code Snippet 14 shows how to create a JSplitPane with components placed side by side and added it
to the frame.
Code Snippet 14:
JFrame frmExplorer; JSplitPane spnExplorer;
// Creates a frame
frmExplorer = new JFrame(“Explorer”);
// Creates a splitpane
spnExplorer = new JSplitPane();
// Adds the splitpane to the frame
frmExplorer.getContentPane().add(spnExplorer);

Concepts

Figure 5.12 shows the output for Code Snippet 14.

Figure 5.12: Output - JSplitPane with Components
V 1.0 © Aptech Limited

5

Session

Lists and Panes

Code Snippet 15 shows how to create a JSplitPane with the horizontal orientation, continuous layout,
and panel added to the right and left side.
Code Snippet 15:
JSplitPane spnExplorer; JPanel pnlLeft, pnlRight;
// Create a frame
frmExplorer = new JFrame(“Explorer”);
// Create a splitpane with the given orientation and continuous layout.
spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,
pnlLeft,pnlRight);
// Add the splitpane to the frame frmExplorer.getContentPane().add(spnExplorer);

Figure 5.13 shows the output for Code Snippet 15.

Figure 5.13: Output – JSplitPane with Horizontal Orientation

5.5.1 Configuring and Displaying JSplitPane
To add two components with the desired orientation, you use the constructor of the JSplitPane. The
components are configured based on the orientation used.
The orientation JSplitPane.VERTICAL_SPLIT places the two components one below the other.

V 1.0 © Aptech Limited

Concepts

The orientation JSplitPane.HORIZONTAL_SPLIT places the two components side by side.

Session

5
Lists and Panes

Figure 5.14 displays the configuring and displaying of JSplitPane.

Figure 5.14: Configuring and Displaying of JSplitPane

5.5.2

Methods of JSplitPane

To display the JSplitPane, you add its instance to a container. The JSplitPane can be configured
using the methods listed in table 5.17.

Method

Description

void setOneTouchExpandable(boole The setOneTouchExpandable() method is used to
an)
activate the feature of one touch expansion of the split

panes. This feature is Look-And-Feel dependent and
not available by default. Set true to activate.
Example: spnExplorer.setOneTouchExpandabl

Concepts

void setDividerLocation(int)

e(true);

The method is used to programmatically set the
divider location of the split pane. The minimum and
preferred size of the component is used to determine
the initial location of the divider.
Example: spnExplorer.

setDividerLocation(200);

Table 5.17: Methods of JSplitPane

V 1.0 © Aptech Limited

5

Session

Lists and Panes

5.6 JLayeredPane
Each container component that acts as top-level container defines a set of panes. At the top of the
hierarchy, there is a root pane which is an instance of JRootPane. The main purpose of the JRootPane
object is to manage other panes which comprises of glass pane, content pane, and layered pane.
Figure 5.15 shows the panes in a container.

Figure 5.15: Container Layers
The layered pane is an instance of JLayeredPane which positions the components based on their Zorder in the container. The Z-order specifies the depth value for the components while positioning them
in the container. The value for the components depth is specified as an integer while adding it to the
container.
The JLayeredPane API defines several layers that allow the components to overlap each other based
on their depth value. Higher the depth value, closer the component occupying the top position in the
container. The top position components are overlapped with the components with a lower depth value.
Figure 5.16 showing a JLayeredPane.

Note: JDesktopPane is a JLayeredPane subclass that is used specifically of holding internal frames.

5.6.1 Configuring a JLayeredPane
When a default JRootPane is created for a class that implements RootPaneContainer, the JRootPane
creates a JLayeredPane for its component area. The JLayeredPane has only a single constructor.

V 1.0 © Aptech Limited

Concepts

Figure 5.16: JLayeredPane

5

Session

Lists and Panes

Syntax:
public JLayeredPane()

Code Snippet 16 shows how to create a JLayeredPane.
Code Snippet 16:
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(310, 320));
layeredPane.setBorder(BorderFactory.createTitledBorder(“Move the mouse”));
layeredPane.addMouseMotionListener(new MouseMotionAdapter() {
...
});

5.6.2 Adding Child Components to JLayeredPane
The layer can be set with layout manager constraints when a component is added to it.
The JLayeredPane has six predefined constants for special values. These constants are listed in table
5.18.

Constant

FRAME_CONTENT_LAYER
PALETTE_LAYER
MODAL_LAYER
POPUP_LAYER
DRAG_LAYER

Description
At level 30000 for holding the menu bar and the content
pane.
Level 0 to hold normal components.
Level 100 for holding floating toolbars and the similar
components.
Level 300 for holding popup menus and tooltips.
Level 400 to ensure the dragged objects remain on top.

Table 5.18: Constants Defined for JLayeredPane

Concepts

When adding components to JLayeredPane, the user can specify any depth apart from those specified
in table 5.18. Any component added is given a layer and a position. When the first component is added,
it is at position zero. Subsequent components added are given higher positions than those added before.
So lower the position of a component, the closer it will appear to the top of the JLayeredPane.
The syntax to add a child component to a JLayered pane is as follows:
Syntax:
layeredPane.add(label, new Integer(i));

where,

i: Is an integer value that refers to the depth of the component in the JLayeredPane.

V 1.0 © Aptech Limited

5

Session

Lists and Panes

Some of the methods of the JLayeredPane are listed in table 5.19.

Method

addImpl()

Description
Adds the specified component to this container at the specified
index. This also notifies the layout manager to add the component
to this container’s layout using the specified constraints object
via the addLayoutComponent method.
Syntax:
protected void addImpl(Componentcomp,
constraints, int index)

Object

where,
comp: Is the component to be added.
Constraints: Is the object expressing the constraints for

this layout.

index: Is the position at which the component is to be

added.
getComponentsInLayer()

Return components of a specified layer in array format.
Syntax:
public Component[] getComponentsInLayer(int
layer)

where,
layer: Is an integer specifying the layer from which the

components are to be extracted.
getIndexOf()

Returns the index of a specified component.
Syntax:
public int getIndexOf(Component c)
c: Is the component whose index is returned.

V 1.0 © Aptech Limited

Concepts

where,

Session

5
Lists and Panes

Method

moveToFront()

Description
Moves the specified component to the top in its current layer.
Syntax:
public void moveToFront(Component c)

where,
c: Is the component to be moved.
moveToBack()

Moves the specified component to bottom position in its current
layer.
Syntax:
public void moveToBack(Component c)

where,
setPosition()

c: Is the component to be moved.

Moves the specified component to a specified position within its
current layer. Zero is the topmost position and -1 is the bottom
most position in a layer.
Syntax:
public void setPosition(Component c, int
position)

where,
c: Is the component to be moved.
position: Is an integer between the value 0 and -1 which

specifies the position of the component in the layer.

Concepts

Table 5.19: Methods of JLayeredPane

V 1.0 © Aptech Limited

5

Session

Lists and Panes

5.7 Check Your Progress
1.

Which of the statements about JComboBox and its event handling are true?
A.
B.
C.
D.
E.
(A)
(B)

2.

Registering an ActionListener to handle the event of a JComboBox is preferred
over ItemListener.
A JComboBox is a combination of a drop-down and a TextField.
ActionListener can trap events of new item being selected and the previous item
being deselected.
The method addItemListener() is used to register the ItemListener event handler.
The JComboBox allows you to type a new item which is not available in the dropdown.
A, B, and C
C, D, and E

(C)
(D)

B, C, and D
B, D, and E

You are trying to add the combo box to the panel and allow the user to input the text. Which one of
the following codes will help you to achieve this?
A.

JPanel pnlFonts = new JPanel();
String[] strFonts = new String[10];
...
...
JComboBox cboFonts
setEditable(true);

B.

= new JComboBox(strFonts); cboFonts.

pnlFonts.add();
JPanel pnlFonts = new JPanel();
String[] strFonts = new String[10];
...
...

C.

JComboBox cboFonts
= new JComboBox(strFonts); cboFonts.
setEditable(false); pnlFonts.add(cboFonts);
JPanel pnlFonts = new JPanel();
...
...
JComboBox cboFonts
= new JComboBox(); cboFonts.
setEditable(true); pnlFonts.add(cboFonts);

V 1.0 © Aptech Limited

Concepts

String[] strFonts = new String[10];

Session

5
Lists and Panes
D.

JPanel pnlFonts = new JPanel();
String[] strFonts = new String[10];
...
...
JComboBox cboFonts
= new JComboBox(strFonts); cboFonts.
setEditable(true); pnlFonts.add(cboFonts);

3.

Which of the statements about JTabbedPane and its event handling are true?
A.
B.

D.
E.

A ChangeListener object cannot be registered with a JTabbedPane.
Each component added to JTabbedPane has a tab, which can have a textual label or
an icon.
In JTabbedPane, several panels can be clubbed together to occupy the same space
in the GUI.
The addTabPane() method is used to add a tab to JTabbedPane.
The default tab placement of a JTabbedPane is top.

(A)
(B)

B, D, and E
C, D, and E

C.

4.

(C)
(D)

B, C, and E
A, C, and D

You are trying to add a panel with the title and icon to the JTabbedPane. Which one of the following
codes will help you to achieve this?
A. JPanel pnlBackground;
JTabbedPane tpnProperties;
. . .

B.

ImageIcon
iconEnglish
=
new
ImageIcon(“background.gif”);
tpnProperties.addTab(“Background”,pnlBackground,iconEnglish);
JPanel pnlBackground;
JTabbedPane tpnProperties;
. . .

Concepts

C.

ImageIcon
iconEnglish
=
new
ImageIcon(“background.gif”);
tpnProperties.add(“Background”,pnlBackground,iconEnglish);
JPanel pnlBackground;
JTabbedPane tpnProperties;
. . .
ImageIcon
iconEnglish
=
new
ImageIcon(“background.gif”);
tpnProperties.addtab(“Background”,iconEnglish,pnlBackground);

V 1.0 © Aptech Limited

5

Session

Lists and Panes

D. JPanel pnlBackground;
JTabbedPane tpnProperties;
. . .
ImageIcon
iconEnglish
=
new
ImageIcon(“background.gif”);
tpnProperties.addTab(“Background”,iconEnglish,pnlBackground);

5.

Which of the following statements about JSplitPane are true?
A.
B.
C.
D.
E.
(A)
(B)

6.

The two components in the JSplitPane can be displayed horizontally (side by side)
or vertically (one below the other).
JSplitPane cannot dynamically change the sizing requirements per component
basis.
The left component is displayed at the right or bottom.
The right component is displayed at the left or top.
The divider can be dragged to specify how much of the total area is to be given to a
component.
A and C
A and E

(C)
(D)

A, B, and E
A, C, and D

You are trying to create a split pane with horizontal orientation, continuous layout, and set the divider
location at 200 pixels. Which one of the following codes will you use to achieve this?
(A) JFrame frmExplorer; JSplitPane spnExplorer;
frmExplorer = new JFrame(“Explorer”);
spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
spnExplorer.setDividerLocation(200); frmExplorer.
getContentPane().add(spnExplorer);
(B) JFrame frmExplorer; JSplitPane spnExplorer;
frmExplorer = new JFrame(“Explorer”);
spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true); spnExplorer.setDividerLocation(200); frmExplorer.
getContentPane().add(spnExplorer);
(C) JFrame frmExplorer; JSplitPane spnExplorer;
spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
false); spnExplorer.setDividerLocation(200); frmExplorer.
getContentPane().add(spnExplorer);

V 1.0 © Aptech Limited

Concepts

frmExplorer = new JFrame(“Explorer”);

Session

5
Lists and Panes
(D) JFrame frmExplorer; JSplitPane spnExplorer;
frmExplorer = new JFrame(“Explorer”);

Concepts

spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true); spnExplorer.setDividerLocation(2000); frmExplorer.
getContentPane().add(spnExplorer);

V 1.0 © Aptech Limited

5

Session

Lists and Panes

5.7.1 Answers
D
D
C
D
B
B

Concepts

1.
2.
3.
4.
5.
6.

V 1.0 © Aptech Limited

Session

5
Lists and Panes

Summary

The JColorChooser class creates a component that allows you to choose a color dynamically.

The JList is a component that displays a group of objects in one or more columns for the user to
choose from.

The JComboBox combines a button or editable field and a drop-down list. This lets the user select
a value from the drop-down list and also provide value through the editable field.

The JTabbedPane class allows several components to share the same space. The user is given
the freedom to choose which components to view by selecting the tab of the desired component.

JSplitPane divides two components. The two components are graphically divided based on the

look and feel implementation.

A container gets its depth from the JLayeredPane. It allows components to overlap each other
when needed.

Components are placed at specified depth along their Z-axis. Higher numbered components are
placed in top of lower numbered components.

Concepts

V 1.0 © Aptech Limited

Session 6
Advanced Swing Components
Welcome to the Session, Advanced Swing Components.
This session explains advanced controls available in Swing API that provide
features, such as sorting, filtering, and displaying views. This session
describes JTable component that displays data in a table of cells and
JTree component that uses hierarchical way to display data. The session
also discusses Drag and Drop feature associated with some of the Swing
components.
In this Session, you will learn to:
 Explain JTable
 Explain how to create a JTable with a custom data model
 Explain event handing of JTable
 Explain JTree
 Explain how to add, configure, and display a JTree
 Explain event handing of JTree
 Explain concept of Drag and Drop
 Explain TransferHandler class
 Explain how to import and export data

6

Session

Advanced Swing Components

6.1 Introduction
A JTable is a component which displays data in a two dimensional format. A JTable is similar to a
spread-sheet in appearance. A JTable does not support scrolling inherently; a JScrollPane is used
to provide the scrolling facility.
A JTable has two distinct parts:

Column Header - A single dimensional row of column header.

Data - A two dimensional rows and columns of data.

Figure 6.1 displays a JTable.

Figure 6.1: JTable

6.1.1 Construction of JTable
A JTable is created using any one of the constructors listed in table 6.1.
public JTable()

Description

Creates a JTable with a default
table model with no initial data
or column.
public JTable(int
Creates a JTable with the
numRows, int numColumns) specified rows and columns with
no initial data or columns.

Example

JTable tblReports = new
JTable();
int rows = 10;
int cols = 5;
JTable

tblReports;

tblReports = new
JTable(rows, columns);

V 1.0 © Aptech Limited

Concepts

Constructor

Session

6
Advanced Swing Components

Constructor

Description

public JTable(Object[][] Creates a JTable with the
data, Object[] columns) specified arrays data and

columns.

Example

JTable tblReports;
String[][] data;
String[] columns;
// Initialize columns
array
. . .
// Initialize data array
. . .

public JTable(Vector
data, Vector columns)

Creates a JTable with the
specified vectors data and
columns.

tblReports = new
JTable(data, columns);
JTable

tblReports;

Vector data;
Vector columns;
// Initialize the
columns
// vector
. . .
// Initialize the data
vector
. . .

Concepts

public JTable(TableModel Creates a JTable with the
model)
specified table model.

tblReports = new
JTable(data, columns);
JTable tblReports;
ReportTableModel
rptModel;// Inner class
// which extends //
AbstractTableModel

The argument, model is an
object of any class which
implements the TableModel
interface. Typically a class
which extends javax.table. tblReports = new
AbstractTableModel is used. JTable(rptModel);
Table 6.1: Constructor Methods of JTable

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Note: A JTable is very useful to display and edit large amount of data in a tabular form. A column

header can be dragged and placed in a new location. Several methods are available to customize the
JTable.

6.1.2 Displaying a JTable
A JTable can be added to the container like any other component. However, to support scrolling a
JTable is typically added to a JScrollPane.
To add and display a JTable, perform the following steps:

Instantiate a JTable object.

Instantiate a JScrollPane and pass the JTable object as a parameter.

Add the JScrollPane to the container.

The JScrollPane manages the vertical scrolling properly by default.
Figure 6.2 displays the JTable.

Figure 6.2: Displaying JTable
Code Snippet 1 shows how to add the table to the frame.

Concepts

Code Snippet 1:
JFrame frmReports;
JTable tblReports;
Vector vecData;
Vector vecColumns;

V 1.0 © Aptech Limited

Session

6
Advanced Swing Components

JScrollPane scpScroller;
// Initialize the vectors data and columns
...
// Creates a table with the specified data and columns
tblReports = new JTable(data, columns);
// Provides the table to the scrollpane to facilitate scrolling
scpScroller = new JScrollPane(tblReports);
// Adds the scrollpane to the frame frmReports.getContentPane().
add(scpScroller);

Figure 6.3 shows the output for Code Snippet 2.

Figure 6.3: Output for Code Snippet 2

6.1.3 Drawbacks of JTable
Concepts

The main drawbacks of JTable are as follows:

All columns are of the same width by default.

Ellipsis is used for displaying data if the column width is smaller.

Horizontal scrolling will not be activated because of ellipsis.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

6.1.4 Solutions to Drawbacks
The JTable makes all the columns of same width by default. If the width of a column is smaller than the
minimum required, an ellipsis is used. Only the first few characters with “…” appended is displayed in
that column. To overcome this problem, you will have to customize the JTable and its header to allocate
appropriate width.
When you create a JTable with arrays or vector it has one major drawback. If the data changes, the new
data is not reflected in the table. You have to instantiate the table again which is expensive in terms of
time and memory. To circumvent this problem and exploit more features you work with a table model.
Figure 6.4 displays the solution to the drawbacks.

Figure 6.4: Solution to Drawbacks
Note: Horizontal scrolling requires you to customize the JTable to a little extent. To circumvent

problems and exploit more features you work with a table model.

6.1.5 Methods of JTable
The following methods of the JTable class are as follows:

print()

The print() method is used to print the columns and rows of the table. This method uses the
default print mode JTable.FIT_WIDTH. A modal print dialog box with a button labeled “Abort”
is displayed throughout the duration of printing.
public boolean print() throws PrinterException

where,

boolean: is the return type, a true is returned if the printing completes, a false is returned

if the printing is aborted.

V 1.0 © Aptech Limited

Concepts

Syntax:

6

Session

Advanced Swing Components

Code Snippet 2 shows how to print the contents of the table with the default print mode.
Code Snippet 2:
JTable tblReports;
String[][] data;
String[] columns;
// Initialize the columns array
...
// Initialize the data array
...
tblReports = new JTable(data, columns);
// Prints the content of the table with default mode JTable.FIT_WIDTH
try
{
table.print();
}
catch(PrintingException ex)
{
System.out.println(“Exception : “ + ex.getMessage());
}

print(JTable.PrintMode printMode)

The print() method is used to print the columns and rows of the table. This method uses the
specified print mode. A modal print dialog box with a button labeled ‘Abort’ is displayed throughout
the duration of printing.
Syntax:
public boolean print(JTable.PrintMode printMode) throws PrinterException

Concepts

where,

printMode: specifies the mode of printing, the valid values are JTable.FIT_WIDTH and
JTable.FIT_NORMAL. The mode JTable.FIT_WIDTH scales the output if necessary, and
JTable.FIT_ NORMAL prints the table in the current size.
boolean: is the return type, a true is returned if the printing completes, a false is returned

if the printing is aborted.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Code Snippet 3 shows how to print the contents of the table with the specified mode to print in
normal width.
Code Snippet 3:
JTable tblReports; String[][] data; String[] columns;
// Initialize the columns array
...
// Initialize the data array
...
tblReports = new JTable(data, columns);
// Print the contents of the table with the current size try
{
table.print(JTable.FIT_NORMAL);
}
catch(PrintingException ex)
{
System.out.println(“Exception : “ + ex.getMessage());
}

print(JTable.PrintModeprintMode, MessageFormatheader,MessageFormat
footer)

The print() method is used to print the columns and rows of the table. This method uses the
specified print mode. A MessageFormat object is used to specify the text to be printed as header
and footer.
Syntax:
Public boolean print(JTable.PrintModeprintMode,
MessageFormat footer) throws PrinterException;

MessageFormatheader,

printMode: Specifies the mode of printing, the valid values are JTable.FIT_WIDTH and
JTable.FIT_NORMAL.
header: Is an object of the MessageFormat class and specifies the header text to print.
footer: Is an object of the MessageFormat class and specifies the footer text to print.
boolean: Is the return type, a true is returned if the printing completes, a false is returned

if the printing is aborted.

V 1.0 © Aptech Limited

Concepts

where,

6

Session

Advanced Swing Components

Code Snippet 4 shows how to print the contents of the table with the specified mode and with
header and footer.
Code Snippet 4:
JTable tblReports; String[][] data;
String[] columns;
// Initialize the columns array
...
// Initialize the data array
...
tblReports = new JTable(data, columns);
// Print the contents of the table with the current size
try {
// Create a header to print “Page 1”, “Page 2” and so on
MessageFormat header = new MessageFormat(“Page {0}”);
// Create a footer to print “- 0 –“, “- 1-“ and so on MessageFormat footer = new
MessageFormat(“- {0} -”); table.print(JTable.PrintMode.FIT_WIDTH, header,
footer);
...
}
catch(PrintingException ex)
{

Concepts

System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Figure 6.5 shows the output for Code Snippet 4.

Figure 6.5: Output for Code Snippet 4

6.1.6 Creating a Custom JTable
A custom data model for JTable can be an object of any class which implements the javax.swing.
table.TableModel interface. Generally, you do not implement this interface directly.
Two default implementations are provided for convenience. You create a concrete implementation of a
TableModel by sub-classing one of the default implementations mentioned as follows:

AbstractTableModel

The abstract class AbstractTableModel provides an abstract implementation of TableModel
interface.

DefaultTableModel

The DefaultTableModel is a concrete implementation of the TableModel interface which
uses vectors to store the data and columns. All the methods of the TableModel interface are
implemented.

Typically the AbstractTableModel is sub classed to provide a concrete implementation. Generally,
the data model class constructor receives the two-dimensional array data and the single-dimensional
array columns. Subsequently, when the data changes a user defined method should be provided
in the data model class to reassign the new data. To reflect the changes in the table you invoke the
FireTableDataChanged() method of the AbstractTableModel class.
Table 6.2 lists the methods that need implementation in case of AbstractTableModel.

Method

public int
getRowCount()

Description
Returns the number of rows. In case the data is a two
dimensional array, the attribute length is returned.

V 1.0 © Aptech Limited

Concepts

6.1.7 AbstractTableModel Interface

Session

6
Advanced Swing Components

Method

Description

public
getColumnCount()

int Returns the number of columns. In case the column

is a single dimensional array, the attribute length is
returned.
public
Object Returns the value of the element at the specified row
getValueAt(int row, int and column.
column)

Table 6.2: Methods of AbstractTableSession

Code Snippet 5 shows how to provide a concrete implementation for a custom table model and add new
data.
Code Snippet 5:
import javax.swing.*; import javax.swing.table.*;
public class ReportTable extends AbstractTableModel
{
// Arrays to hold data and columns String[][] data;
String[] columns;
...
// Construct to initialize the model with data and columns public ReportTable
(String[][] data, String[] columns)
{
// Initialize the data and columns this.data = data;
this.columns = columns;
}
// A user defined method to set new data
// This method should be called subsequently when data changes

Concepts

public void setData(Object[][] data)
{
this.data= data;
fireTableDataChanged();
}
public int getRowCount()

{

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

return data.length;

}

public int getColumnCount()
{

return column.length;

}
public Object getValueAt(int row, int column) { return data(row,column);
}
Note: The user-defined method setData() invokes the method fireTableDataChanged() of the
AbstractTableModel class. The fireTableDataChanged() method notifies the JTable to update the
view. If the fireTableDataChanged() is not invoked then the new data will not be reflected in the

table.

6.1.8 Methods of JTable
Once your model class is ready, perform the following steps:

Instantiate data model class

Before you instantiate the data model class object, you create the two-dimensional data array, and
the single-dimensional column array. Next you declare and instantiate the data model class object
and send the data and column array as arguments.
Code Snippet 6 shows how to create the data and columns array and instantiate the data model.
Code Snippet 6:
ReportTable reportTable; String[][] data; String[] columns;
// Initialize data and columns
String[][] data = { {…}, {…} };
String[] columns = {“…”, “…”};
...
// the arrays
reportTable = new ReportTable(data, columns);

Instantiate JTable with data model object

Once the data model object is ready, you declare the table object and instantiate it by passing the
data model object as an argument in the constructor.

V 1.0 © Aptech Limited

Concepts

// Instantiate the data model reportTable with the data and columns from

Session

6
Advanced Swing Components

Code Snippet 7 shows how to declare a table and instantiate it with a table model object.
Code Snippet 7:
JTable tblReports;
ReportTable reportTable;
String[][] data;
String[] columns;
// Instantiates the table tblreports with the data model object
tblReports = new JTable(reportTable);
...
// Whenever the data Changes replace the new data into the two dimensional
array
// Assigns the new data to the model by invoking setData()

6.1.9 Event Handling
Most of the events generated by the JTable are consumed by the table itself. These events are generated
when you click a mouse on the table to select a row. When a user types some data in a particular cell of
the table, the event is generated.
You can typically add a MouseListener to a JTable to detect which row was clicked. Then you can
retrieve the data from the selected row.

6.1.10 Event Handling Using MouseListenerEnhancements
Most of the events of JTable are consumed by the table itself. However, when you select a row in the
table with a mouse click, a mouse event is generated.
To handle the mouse click event the steps listed in table 6.3.

Steps

Concepts

Register a MouseListener

Description
The addMouseListener()
method is used to register
MouseListener object to
handle mouse events. This
method takes an object of
a class which implements
the MouseListener, as an
argument. Typically an anonymous
class of MouseListener or a
MouseAdapter is used.
V 1.0 © Aptech Limited

Example

// Register the mouse
listener to the reports
table tblReports.
addMouseListener(new
MouseAdapter() {
// provides
implementation to the
mouse clicked event
});

6

Session

Advanced Swing Components

Steps

Description

Add the action code in
mouseClicked() method

Both MouseListener and
MouseAdapter have a method
mouseClicked(), which is
invoked as a result of the mouse
being pressed and released.
This method takes an object of
MouseEvent class as argument.

Example

// Register the mouse
listener to the reports
table tblReports.
addMouseListener(new
MouseAdapter() {
// Provide implementation
to the mouse clicked
event public void
mouseClicked(MouseEvent
me) {
// Add the code
. . .
}});

Table 6.3: Steps for MouseListeners
Note: When the mouse is pressed first, the mousePressed() method is invoked and on release,
the mouseReleased() method is invoked. After the mouseReleased() method completes, the
mouseClicked() method is called.

6.2 JTree
The JTree class helps to display data in a defined hierarchy. It does not contain data or a data cache. Like
the JTable it is the user’s view of data. The JTree gets its data by querying the data model.
The JTree has different parts like nodes, branches, leaves.

6.2.1 Understanding a JTree
A JTree is a component which displays its data in a hierarchical way. A JTree can be used to represent
a complex tree like structure of hierarchical data. Hierarchical data cannot be easily represented in terms
of rows and columns. They can be best represented in a tree like structure.
A JTree can be used to display items listed in table 6.4.

Description

The file system on an operating system
Organizational hierarchy
Ancestry details

The file system includes the drive, its root folder
and the sub folders.
The hierarchy includes the top management,
middle management and all other staff.
The details include ancestors and their
predecessor.
Table 6.4: JTree Display

V 1.0 © Aptech Limited

Concepts

Display

Session

6
Advanced Swing Components

Figure 6.6 displays the JTree.

Figure 6.6: JTree

6.2.2 Structure of JTree
A JTree displays data vertically; each row contains only one item called node. Every JTree has a root
node at the top; all other nodes descend from the root node.

Concepts

Initially, except the root node, all branch nodes are in a collapsed state. You typically click the root node
to expand the tree, and then the branch node. Nodes which have children are called branch nodes; they
expand and collapse. A node which does not have children is called a leaf node, it cannot expand and
collapsed.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Figure 6.7 displays the structure of JTree.

Figure 6.7: Structure of JTree

6.2.3 Constructing a JTree
To create a JTree you follow the steps listed in table 6.5.

Steps
Create an instance of

DefaultMutableTreeNode

Description
The javax.swing.tree
package has the class

DefaultMutableTreeNode

to represent a root node,
branch-node or a leaf-node.
To represent the root node,
you create an instance of a

Example

DefaultMutableTreeNode
dmtnRoot;
dmtnRoot= new DefaultMut
ableTreeNode(“Root”);

Create an instance of a JTree

class.
Create an instance of a JTree
and pass the root node as an
argument in the constructor
of a JTree: public
JTree(TreeNode node).

DefaultMutableTreeNode
dmtnRoot; JTree treTree;
// Creates an instance
of a JTree with the root
node as an argument
treTree= new
JTree(dmtnRoot);

Table 6.5: Steps to Create JTree

V 1.0 © Aptech Limited

Concepts

DefaultMutableTreeNode

Session

6
Advanced Swing Components

6.2.4 Configuring and Displaying a JTree
To add, configure, and display a JTree, perform the following steps:

Create instances of DefaultMutableTreeNode to represent the branch nodes and leaf nodes.

Add the branch nodes and leaf nodes to the root node.

Create a JScrollPane and send the tree instance as an argument.

Add the JScrollPane to the container.

Code Snippet 8 shows how to add, configure, and display a JTree.
Code Snippet 8:
JFrame frmTree;
DefaultMutableTreeNode dmtnBranch1, dmtnBranch2, …; DefaultMutableTreeNode
dmtnLeaf1, dmtnLeaf2, …; DefaultMutableTreeNode dmtnRoot;
JTree treTree;
...
// Adds the branch-nodes to the root node dmtnRoot.add(dmtnBranch1); dmtnRoot.
add(dmtnBranch2);. . .
// Adds the leaf-nodes to the branch node dmtnBranch1.add(dmtnLeaf1);dmtnBranch2
.add(dmtnLeaf2);
// Creates a JScrollPane with the tree instance as an argument JScrollPane
scpScroller = new JScrollPane(treTree);

Concepts

// Adds the JScrollPane to the frame frmTree.getContentPane().add(scpScroller);

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Figure 6.8 shows the output for Code Snippet 8.

Figure 6.8: Output for Code Snippet 8

6.2.5 Event Handling Using TreeSelectionListeners
When a node is selected the JTree fires valueChanged() event. A TreeSelectionListener object
is registered to handle this event.
To handle the node selection event, perform the steps listed in table 6.6.

Steps

Description

Register a TreeSelectionListener

Add code in the valueChanged() method

The addTreeSelectionListener()
method is used to register a listener object
with a tree. Any object which implements the
TreeSelectionListener interface is sent as
an argument.
When a node is selected the valueChanged()
method is invoked. You add the action code in this
method. An object of the TreeSelectionEvent
class is passed as an argument to this method.

Table 6.6: Node Selection Event
Code Snippet 9:
JTree treTree;
// Registers the tree selection listener to the tree treTree.addTreeSelectionList
ener(new TreeSelectionListener() {
. . .});

V 1.0 © Aptech Limited

Concepts

Code Snippet 9 shows how to register tree selection listener to the JTree.

Session

6
Advanced Swing Components

Code Snippet 10 shows how to handle the node selection event of the JTree.
Code Snippet 10:
// Registers the tree selection listener to the tree treTree.addTreeSelectionList
ener(new TreeSelectionListener() {
// Handles value change event
public void valueChanged(TreeSelectionEvent e) {
// Add the code to handle the event
}});

6.2.6 Event Handling Using TreeExpansionListeners
To handle the tree expansion event, perform the steps listen in table 6.7.

Steps

Description

Register a TreeExpansionListener

Add code in the treeExpanded()
method
Add code in the treeCollapsed()
method

A TreeExpansionListener object is registered
to handle node expansion or collapse. The
addTreeExpansionListener() method is used
to add an object of the class which implements the
TreeExpansionListener interface.
Whenever a node of a tree expands the method
treeExpanded() is invoked. You write the action code
to handle the node expansion event in this method.
Whenever a node of a tree collapses the method
treeCollapsed() is invoked. You write the action code
to handle the collapsed node event in this method.

Table 6.7: Node Expansion Event
Code Snippet 11 shows how to register tree expansion listener to the JTree.
Code Snippet 11:
JTree treTree;
...

Concepts

treTree.addTreeExpansionListener(new TreeExpansionListener() {
...
});

Code Snippet 12 shows how to handle the node expansion event of the JTree.
Code Snippet 12:
// Registers the tree expansion listener to the tree

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

treTree.addTreeExpansionListener(new TreeExpansionListener()
{
// Handles the node expansion event
public void treeExpanded(TreeExpansionEvent e)
{

// Action code for the event tree expanded

...

}
}

Code Snippet 13 shows how to handle the node collapsed event of the JTree.
Code Snippet 13:
public void treeCollapsed(TreeExpansionEvent evt)
{
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
System.out.println(“treeCollapsed”);
}
}

6.2.7 Event Handling Using TreeWillExpandListener
To handle the treewillexpand event, perform the steps listed in table 6.8.

Steps

Description

Register a

ATreeWillExpandListener

JTree treTree;

The addTreeWillExpand

treTree.addTreeWillExpandL
istener(new TreeWillExpand

Listener() method is

Listener()

Listener

object is registered to handle this
event.

used to add an object of any
class which implements the

TreeWillExpandListener

interface.

V 1.0 © Aptech Limited

. . .

Concepts

TreeWillExpand

Examples

Session

6
Advanced Swing Components

Steps

Description

Add code in the

Whenever a node of a tree is about
to expand the treeWillExpand()
method is invoked. You write the
action code to handle the node
expansion event in this method.

//Register the tree will
expand listener treTree.ad
dTreeWillExpandListener(ne
w TreeWillExpandListener()
{

Whenever a node of a tree
is about to collapse the
treeWillCollapse() method is
invoked. You write the action code
to handle the node collapse event in
this method.

public void
treeWillCollapse
(TreeExpansionEvent e)

TreeWillExpand()

method

Add code in the

treeWillCollapse()

method

Examples

public void treeWillExpand
(TreeExpansionEvent e)
TreeWillExpandListener() {

Table 6.8: TreeWillExpand Event

6.3 Drag and Drop
Modern GUI applications provide the ability to support transfer of data between components in the
application. The data transfer can be done within an application or between the applications. The ability
to transfer the data can be achieved through two ways:

Drag and Drop (DND) support

Clipboard transfer through Cut or Copy or Paste (CCP).

6.3.1 Drag and Drop (DND)
The Swing API provides data transfer facility between the components within the Java application or
between different Java applications through DND technique.

Concepts

The DND can be used to transfer binary data or graphical objects. For example, consider a situation
where an image being dragged between two Java applications, then data transfer is of binary. Similarly,
if a component is dragged, then the transfer is of graphical components.
During a DND operation, the user clicks the mouse over the source, drags the mouse over to the target
and releases the button at the target. The data is transferred using a drag board, which is a clipboard that
is used specifically for Drag and Drop operations.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Figure 6.9 shows the drag and drop flow.

Figure 6.9: Drag and Drop Flow
During the data transfer, a visual feed is given to the user at every instance. Hints are provided as to what
locations will not accept the data and when the target is reached, where to drop the data. The types of
data that can be transferred in this way are text, images, URL, files, bytes, and string.

6.3.2 DND Support for Swing Components

JColorChooser

JEditorPane

JFileChooser

JFormattedTextField

JList

JTable

JTextArea

JTextField

JTextPane

Concepts

The DND support is provided by most swing components inbuilt. Once the setDragEnabled(True)
method is invoked on a component it supports the drag gesture. The following is a list of components
that support the drag gesture:

V 1.0 © Aptech Limited

Session

6
Advanced Swing Components

JTree

Similarly, the components that provide support for drop are as follows:

JEditorPane

JFormattedTextField

JPasswordField

JTextArea

JTextField

JTextPane

JColorChooser

Apart from these components, there are some components which calculates the drop location for
displaying the dragged component. Such component allows the user to specify a drop mode to handle
component details. Few of these components include: JList, JTable, and JTree.
A source can support one or more targets. A target can accept one or more transfer modes. The transfer
mode in a DND operation is determined by the targets supported by the source and the modes supported
by the target.

6.3.3 TransferHandler Class
The TransferHandler class provides an easy mechanism for transferring data between components.
It is used to perform DND operations by performing drag from a component and drop to a component. It
is also used to work with CCP operations that performs data operation through clipboard.
The TransferHandler class provides a constructor method that implements the default behavior for
the data to be transferred by specifying the property name.
Table 6.9 lists the constructors of TransferHandler class.

Constructor

Concepts

TransferHandler()

Description

TransferHandler(String property)

This creates TransferHandler for subclasses.
This method creates a TransferHandler
that can transfer data from one component to
another through drag and drop operation or CCP
operation.
The argument property specifies the name of
the property which need to be transferred.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Constructor

Description
For example, to drag the caption of a button into
some other component, the property named
‘text’ can be specified.

Table 6.9: Constructor Methods of TransferHandler

6.3.4 Built-in DND Mechanism
Most of the Swing components are provided with the default implementation of the transfer handler.
Thus, you need to turn the drag and drop facility ON to perform DND operations on them.
Some of the methods that are supported by the Swing components to enable built-in data transfer are
listed her in table 6.10.

Method

Description

setDragEnabled(boolean)

This method turns on drag support. It is defined for
each component that supports the drag gesture.
setDropMode(DropMode)
This method configures how drop locations are
determined. This method is defined for JList,
JTable, and JTree.
setTransferHandler(Transfer This method is used to plug in custom data
Handler)
import and export facility. This method is
defined in JComponent class, so it is inherited
by every Swing component.
Table 6.10: Methods to engage a TransferHandler on Components
Code Snippet 14 demonstrates the drag of item from JList into a JTextField instance.
Code Snippet 14:
public class DragAndDropDemo extends JFrame {
JTextField field;

public DragAndDropDemo() {
setTitle(“Built-in Drag and Drop”);
setLayout(new GridLayout(1, 2));
// Creates an array and initializes the JList

V 1.0 © Aptech Limited

Concepts

JButton button;

Session

6
Advanced Swing Components

String[] month = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”};
JList l = new JList(month);
field = new JTextField();
field.setBounds(30, 50, 50, 25);
add(field);
add(l);
// Enables the drag on JList
l.setDragEnabled(true);
// Sets the transferable property for the text box
field.setTransferHandler(new TransferHandler(“text”));

setSize(330, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new DragAndDropDemo();
}
}

Concepts

Figure 6.10 shows the output of the Code Snippet 14.

Figure 6.10: Output – Built-in DND
V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

6.3.5 Import and Export Data Using TransferHandler Class
Export methods are used for exporting data from a component. They are invoked for the drag gesture
and copy action when the component is the source of the operation. These methods are listed in table
6.11.

Method

Description

getSourceActions(JComponent)
createTransferable(JComponent)
exportDone(JComponent,
Transferable, int)

This method is used to query what actions are supported
by the source component, such as COPY, MOVE, or
LINK, in any combination.
This method bundles up the data to be exported into a
Transferable object in preparation for the transfer.
This method is invoked after the export is complete.
During a MOVE action, the data is removed from the
source after the transfer is complete.

Table 6.11: Export Methods of Transferable Classes
Code Snippet 15 shows an example of TransferHandler methods for Data export.
Code

Snippet

15:s

int getSourceActions(JComponent a)
{
return COPY_OR_MOVE;
}
Transferable createTransferable(JComponent a) {
return new StringSelection(a.getSelection());
}
void exportDone(JComponent a, Transferable t1, int act) {
if (act == MOVE) {
}
}

Import methods are used for importing data into a component. They are invoked for the drop gesture, or
the paste action, when a component is the target of the operation.

V 1.0 © Aptech Limited

Concepts

c.removeSelection();

Session

6
Advanced Swing Components

The TransferHandler methods for importing data are listed in table 6.12.

Method

Description

c a n I m p o r t ( T r a n s f e r H a n d l e r . This method is called repeatedly during a drag
TransferSupport)
gesture and returns true if the area below the cursor

can accept the transfer, or false if the transfer will be
rejected.
i m p o r t D a t a ( T r a n s f e r H a n d l e r . This method is called on drop or paste operation and
TransferSupport)
starts the transfer of data to the target component.
If the import is successful then this returns true
value.
Table 6.12: Import Methods of Transferable Classes

6.3.6 Drag Gesture
Drag and drop is initiated with a gesture, which is a mouse down followed by mouse drags. Drag gesture
recognizers fire events when drag gestures are detected in an associated component.
Code Snippet 16 shows the drag gesture firing a drag event.
Code Snippet 16:
public DragTree()
{
dragSource.createDefaultDragGestureRecognizer(component, action);
}
public void dragDropEnd(DragSourceDropEvent e){}
public void dragEnter(DragSourceDragEvent e){}
public void dragExit(DragSourceEvent e){}
public void deopActionChanged(DragSourceDragEvent e){}

Concepts

6.3.7 Implementation of DND
Before a Drag and Drop operation is fired, it is necessary to create Drag sources, Drop targets, drag
gesture recognizers, and transferables. Transferables are swing objects that act as a wrapper for data that
are being moved via the drag and drop operation.
Drag source listeners initiate the drag. Drop target listeners handle drop events. Programmer intervention
is needed only for wrapping data in transferables and handling drop.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

The objects involved in as drag and drop operations are as follows:
1.

The startDrag() method is initiated by the Drag source. Drag gesture recognizers are created using
the createDragGestureRecognizer() or the reateDefaultDragGestureRecognizer().

2.

Drop target is linked to a component and a target listener. Whenever target event occur the listener
is notified.

3.

Transferables wrap data to be transferred.

4.

The transfer modes supported by the gesture source are defined, and the data to be transferred is
placed onto the dragboard in the handler of the drag event.

5.

Drag listeners are notified of the drag gesture. The listeners react by initiating drag by invoking
DragSource.startDrag().

6.

Source listeners react to events that occur after the drag is initiated.

7.

Drop target listeners respond to drop events and handle the actual drop of data.

8.

After a drag and drop event is started, any node or scene the mouse moves over is a potential target
for the drop. The target object that receives the data is specified by implementing the Drag _ Over
event handler.

Code Snippet 17 shows the implementation of onDragDetected handler.
Code Snippet 17:
source.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event)
{
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
ClipboardContent cont = new ClipboardContent();
cont.putString(source.getText());
db.setContent(cont);
event.consume();
}

Concepts

});

V 1.0 © Aptech Limited

Session

6
Advanced Swing Components

6.4 Check Your Progress
1.

You are trying to create a JTable from the string array. Which one of the following codes will help
you achieve this?
(A)

JTable tblReports; String[][] data; String columns;
// Initialise the columns
...
// Initialise the data
...
tblReports = new JTable(data,columns);

(B)

Jtable tblReports; String[][] data; String[] columns;
// Initialise the columns
...
// Initialise the data
...
tblReports = new Jtable(data,columns);

(C)

JTable tblReports; String[][] data; String[] columns;
// Initialise the columns
...
// Initialise the data
...
tblReports = new JTable(data,columns);

(D)

JTable tblReports; string[][] data; string[] columns;
// Initialise the columns
...
// Initialise the data

Concepts

...
tblReports = new JTable(data,columns);

V 1.0 © Aptech Limited

6

Session
2.

Advanced Swing Components

Which of these statements about JTable are true?
A.
B.
C.
D.
E.

The JTable makes all the columns of same width by default.
Horizontal scrolling will be activated because of ellipsis.
If the data changes then the new data is not reflected in the table.
Only the last few characters with “…” appended is displayed in smaller width column.
You have to instantiate the table again to reflect the data changes.

(A) A, C, and E
(B) C, D, and E
3.

(C)
(D)

Can you match the features of JTable against their description?
Features

(A)
(B)
(C)
(D)
(E)

DefaultTableModel
getColumnCount()
getValueAt()

getRowCount()

AbstractTableModel

(A) A-4, B-2, C-5, D-1, E-3
(B) A-3, B-5, C-4, D-1, E-2
4.

A, B, and D
A, C, and D

(1)
(2)
(3)
(4)
(5)

Description
Return number of rows
Return number of columns
Abstract implementation
Concrete implementation
Return data at specified row and
column

(C)
(D)

A-2, B-4, C-3, D-1, E-5
A-5, B-2, C-4, D-1, E-3

You are trying to register a MouseListener to the JTable and handle the mouse clicked event.
Which one of the following codes will help you to achieve this?
(A)

tblReports.addMouseListener(new MouseAdapter() { public void
MouseClicked(MouseEvent me) {
//

Click code. . .

}

(B)

});
tblReports.addMouseListener(new MouseAdapter() { public void
mouseClicked(MouseEvent me) {
//

Click code. . .

Concepts

}
});

V 1.0 © Aptech Limited

Session

6
Advanced Swing Components
(C)

tblReports.addMouseListener(new MouseAdapter { public void
mouseClicked(MouseEvent me) {
//

Click code

. . .}

(D)

});
tblReports.addMouselistener(new
mouseClicked(MouseEvent me) {
//

MouseAdapter()

{

public

void

Click code

. . .
}
});

5.

6.

Which of the following statements about JTree are true?
(A)
(B)
(C)
(D)
(E)

A JTree displays data vertically, each row contains only one item called node.
Every JTree has a root node at the bottom.
Initially, except the root node, all branch-nodes are in a collapsed state.
Nodes which have children are called branch-nodes.
A leaf-node can expand and collapse.

(A)
(B)

A, B, and E
C, D, and E

(C)
(D)

A, B, and D
A, C, and D

You are trying to add a branch node and a leaf node to the JTree and display a JTree. Which one
of the following codes will help you to achieve this?
(A)

JFrame frmTree; DefaultMutableTreeNode dmtnBranch1;
DefaultMutableTreeNode dmtnLeaf1,dmtnRoot; JTree treTree;
. . .
dmtnRoot.add(dmtnBranch1); dmtnBranch1.add(dmtnLeaf1);

Concepts

JScrollPane scpScroller

= new JScrollPane(dmtnBranch1);

frmTree.getContentPane().add(scpScroller);

V 1.0 © Aptech Limited

6

Session
(B)

Advanced Swing Components

JFrame frmTree; DefaultMutableTreeNode dmtnBranch1;
DefaultMutableTreeNode dmtnLeaf1,dmtnRoot; JTree treTree;
. . .
dmtnRoot.add(dmtnLeaf1); dmtnBranch1.add(dmtnBranch1);
JScrollPane scpScroller

= new JScrollPane(treTree);

frmTree.getContentPane().add(scpScroller);

(C)

JFrame frmTree; DefaultMutableTreeNode dmtnBranch1;
DefaultMutableTreeNode dmtnLeaf1,dmtnRoot; JTree treTree;
. . .
dmtnRoot.add(dmtnBranch1); dmtnBranch1.add(dmtnLeaf1);
JScrollPane scpScroller

(D)

= new JScrollPane(dmtnRoot);

frmTree.getContentPane().add(scpScroller);
JFrame frmTree; DefaultMutableTreeNode dmtnBranch1;
DefaultMutableTreeNode dmtnLeaf1,dmtnRoot; JTree treTree;
. . .
dmtnRoot.add(dmtnBranch1); dmtnBranch1.add(dmtnLeaf1);
JScrollPane scpScroller

= new JScrollPane(treTree);

frmTree.getContentPane().add(scpScroller);

7.

Can you match the methods invoked against their events?
Methods

(A)
(B)
(C)
(D)
(E)

treeCollapsed()
valueChanged()
treeExpanded()

treeWillExpand()

treeWillCollapse()

(C)
(D)

A-2, B-1, C-3, D-5, E-4
A-5, B-2, C-4, D-1, E-3

Concepts

(A) A-4, B-2, C-5, D-1, E-3
(B) A-3, B-5, C-4, D-1, E-2

(1)
(2)
(3)
(4)
(5)

Events
Node of a tree is selected
Node of a tree collapses
Node of a tree expands
Node of a tree is about to collapse
Node of tree is about to expand

V 1.0 © Aptech Limited

Session

6
Advanced Swing Components

6.4.1 Answers
C
A
A
B
D
D
C

Concepts

1.
2.
3.
4.
5.
6.
7.

V 1.0 © Aptech Limited

6

Session

Advanced Swing Components

Summary
The JTable is a class that allows data to be displayed and edited in table form. It is simply the user’s
view of data and does not contain data or cache data.

The JTable filter and sort through data. This is enabled by the RowSorter() method columns in a
JTable may be arranges differently in the view than in the modal, but this does not affect the data
in any way.

The JTree class displays a set of hierarchical data as an outline or a tree. The tree had nodes,
branches and leaves. Each data row that is displayed is a node.

Nodes are non leaf nodes that display all the children when the parent is expanded. A collapsed
node hides all its children. Nodes that have children are Branch nodes.

The ability to transfer data between components in an application is very essential. The DND
feature of Java swing gives users this ability. While most of the JComponent support DND
inherently, some of them needs the DND to be invoked.

A DND operation occurs between two objects referred to as the gesture source and the gesture
target. The type of transfer between the source and target is specified by the transfer Modes:
Copy, Move, and Link.

Concepts

V 1.0 © Aptech Limited

Session 7
Internationalization
Welcome to the Session, Internationalization.
This session provides a brief introduction to the development of software
applications for the global market. The module highlights the aspects
related to internationalization and localization of applications, which are
country, language, and region neutral. Internationalized applications need
to be meticulously planned, failing which may result in costly application
re-engineering.
In this Session, you will learn to:
 Explain the need of Internationalization
 Explain the concept of Localization
 Describe how to create a properties file to store locale-specific
data
 Describe how to define a Locale for a country
 Explain how to use the ResourceBundle class
 Explain how to retrieve locale-specific data from the
properties file
 Explain the need and procedure for formatting numbers,
currencies, and percentages
 Explain the need and procedure for formatting Date and Time
 Explain the need and procedure for using the MessageFormat
class

Session

7
Internationalization

7.1 Introduction
With the advent of the Internet and Web based programming, globalization of software products has
become an imminent requirement. Some of the problems that should be addressed in the globalization
of software products include:

Countries across the world do not speak or understand English language.

The currency symbol varies across countries.

Date and Time are represented differently in different countries.

Spellings of words vary amongst countries.

7.1.1 Alternatives to Solve the Problem
Three possible options to solve the issues related to globalized software are as follows:

Develop the entire product in the desired language
This option will mean repetition of coding work. It is a time-consuming process and not an acceptable solution. Development cost will be much higher than the one time cost.

Translate the entire product to the desired language
Successful translation of the source files is very difficult. The menus, labels, and messages of most
GUI components are hard-coded in the source code. It is not same as that a developer or a translator will have linguistic as well as coding skills.

Use internationalization
Provide ability in application to adapt to various countries, languages.

7.1.2 Meaning of Internationalization

Concepts

The process of creating applications which can adapt and adjust to various countries, languages, and
regions is known as internationalization. There are 18 letters between the first ’i’ and the last ’n’, hence,
the word ‘internationalization’ is often abbreviated as i18n.
Internationalized software is developed independent of the countries or language of its users, and then
localized for multiple countries or regions. Internationalized software should be developed, such that it
can be adapted without any engineering changes.

V 1.0 © Aptech Limited

7

Session

Internationalization

Figure 7.1 depicts an example of internationalization.

Figure 7.1: Example of Internationalization

7.1.3 Meaning of Localization
The process of adapting an application for a specific language or country by addition of locale-specific
components and translation of text is referred to as localization. Since, there are 10 letters between the
’l’ and ’n’, the word localization is often abbreviated as l10n.

Concepts

The translation of text is the most time-consuming part of the localization process. Localization also
needs to see to it that the formatting of dates and currencies conforms to the requirements of the specific
country.

V 1.0 © Aptech Limited

Session

7
Internationalization

Figure 7.2 displays an example of localization.

Figure 7.2: Example of Localization

7.1.4 Benefits of I18N and L10N

Concepts

An internationalized and localized application has the following benefits:

With the addition of localized data, the same executable application can run worldwide.

Textual elements such as labels and messages for GUI components are not hard-coded in the
program.

Textual elements are stored outside the source code and retrieved dynamically.

Support for new languages does not require recompilation.

Culturally dependent data, such as dates and currencies, appear in formats that conform to the
end-user’s region and language.

Internationalized programs are localized quickly.

V 1.0 © Aptech Limited

7

Session

Internationalization

7.1.5 Unicode
Unicode provides a unique number for every character irrespective of platform, program, or language.
Before Unicode was invented, there were several different encoding systems for assigning numbers to
characters. No single encoding system contained enough number of characters to address international
languages.
The encoding systems contradicted with each other, that is, two encoding systems had same number for
two different characters, or had different numbers for the same character.
Unicode is a 16-bit character encoding system that supports the world’s major languages. The primitive
data type char in Java is based on Unicode encoding.
Figure 7.3 displays Unicode.

Figure 7.3: Unicode

The Java platform uses Unicode as its native character encoding. However, Java programs still need to
handle characters in other encoding systems. The String class can be used to convert standard encoding
systems to and from the Unicode system.
To indicate Unicode characters that cannot be represented in ASCII, such as ö, you use the \uXXXX escape
sequence. Each X in the escape sequence is a hexadecimal digit.

V 1.0 © Aptech Limited

Concepts

7.1.6 Significance of Unicode

Session

7
Internationalization

Code Snippet 1 shows how to indicate the ö character with an escape sequence.
Code Snippet 1:
String str = ”\u00F6”; char c = ’\u00F6’;
Character letter = new Character(‘\u00F6’);

7.2. Internationalization Process
The steps to be followed through the process of internationalization are as follows:

Create a properties file

Define a Locale

Create a ResourceBundle

Fetch the text strings from the ResourceBundle

7.2.1 Introduction to Properties File
A properties file is a plain text file, which contains the information that is translated into an internationalized
program. A default properties file with any name, but having an extension as .properties contain the
‘key = value’ pair in English.
The keys on the left-hand side are not translated, whereas the values on the right-hand side are translated.
These translated values are kept in different files for different languages and countries. The naming
convention of such a file is DefaultFileName_lc_CC.properties. The ‘lc’ represents the language
code in lower case and ‘CC’ the country code in upper case.

7.2.2 Creating the Properties File

Concepts

To create a properties file, you can use any plain text editor such as a Notepad. For each language and
country, you create a properties file with the naming convention. A country can have more than one
language.

V 1.0 © Aptech Limited

7

Session

Internationalization

Some examples of properties files which contain messages are listed in table 7.1.

Properties File

Description

MessageBundle.properties

greetings = Hello.

Farewell = Goodbye.
MessageBundle_fr_FR.properties

Inquiry = How are you?
Greetings = Bonjour.
farewell = Au revoir

MessageBundle_de_DE.properties

inquiry = allez-vous?
Greetings = Hallo
Farewell = Tschüß
Inquiry = Wie geht’s?

Table 7.1: Messages in Properties File

7.2.3 Defining the Locale
A Locale is simply an identifier for a particular combination of language and region. A java.util.
Locale class object represents a specific geographical, political, or cultural region. Any operation that
requires a locale to perform its task is said to be locale-sensitive. These operations use the Locale object
to tailor information for the user.
For example, displaying a number is a locale-sensitive operation. The number should be formatted
according to the customs and conventions of a user’s native country, region, or culture.
A Locale object is created using the constructors listed in table 7.2:

Description

Example

public
Creates Locale object with the specified
Locale(String
language and country.
language, String
Here, language argument is the language
country)

/* Creates Locale
object for English
language and US
country */

public
Locale(String
language)

Locale
usLocale = new
Locale(“en”,”US”);
/* Creates Locale
object for English
language */

code consisting of two letters in lowercase
and country argument is the country code
consisting of two letters in upper case.
Creates a Locale object in the specified
language.

Locale enLocale =
new Locale(“en”);

Table 7.2: Locale – Constructor Methods

V 1.0 © Aptech Limited

Concepts

Constructor

Session

7
Internationalization

7.2.4 Locale Class Methods
Some of the important methods of the Locale class are listed in table 7.3.

Method

public static Locale
getDefault()

public final String
getDisplayCountry()

public final String
getDisplayLanguage()

Description

Example

Gets the default Locale for the
instance of the JVM.

Returns the name of the country
for the current Locale, which
is appropriate for display to the
user. For example, if the default
locale is fr_FR, this method will
return France.

/* Retrieve the default
Locale for the JVM */
Locale currentLocale =
Locale.getDefault();
/* Retrieve the country
name in a user-friendly
format */
Locale currentLocale =
Locale.getDefault();
String strCountry =
currentLocale.

getDisplayCountry();
/* Retrieve the language
Returns the name of the
language for the current Locale, name in a user-friendly
format */
in an appropriate format to the
user. For example, if the default
Locale currentLocale =
locale is fr_FR, this method will
Locale.getDefault();

return French.

String strLanguage =
currentLocale.
getDisplayLanguage();

Table 7.3: Methods of Locale Class
Locale class has several methods that can be used for localization of an internationalized application.

Additional methods of the Locale class their general syntax and a brief description of the methods
listed in table 7.4.

Concepts

Method

Description

public static
This method is used to retrieve all the available locale instances.
Locale[]
getAvailableLocales() Here, Locale [] is an array of all available locales.

Example: To retrieve the available locales.
Locale [] locales;
locales = Locale.getAvailableLocales();

V 1.0 © Aptech Limited

7

Session

Internationalization

Method

public String
getCountry()

Description
This method returns an uppercase letter code for the country/region
or an empty string.
Example: To retrieve the country code of the locale.
/* Retrieve the current value of the default locale
for this instance
of the Java Virtual machine */
Locale locale = Locale.getDefault();
// Retrieve the Country code

public String
getLanguage()

String country = locale.getCountry();

This method returns a lowercase letter code for the country or region
or an empty string.
Example: To retrieve the language code for the
current locale.

/* Retrieve the current value of the default locale
for this instance of the Java Virtual Machine */
Locale locale = Locale.getDefault();
// Retrieve the Language code
public final String
getDisplayName()

String language = locale.getLanguage();

The getDisplayName() method is used to retrieve a name for the
locale which is appropriate for user display. The display name returned
will be in language (country), or language or country form.
Example: To retrieve the display name for language
and country.

/* Create a new Locale with the fields language
and country */
Locale locale = new Locale(“fr”, “FR”);
// Retrieve the display name

Concepts

String name = locale.getDisplayName();

V 1.0 © Aptech Limited

Session

7
Internationalization

Method

forLanguageTag ()

Description
If a language tag string conforms to the IETF BCP 47 standard, the
forLanguageTag(String) method can be used. This returns a
locale for the specified language tag string.
Syntax:
public static Locale forLanguageTag (String
langtag1);
where,
Langtag1: Is the language for which locale is
returned.
Example:
Locale oneLocale = Locale.forLanguageTag(“en-US”);
Locale twoLocale = Locale.forLanguageTag(“jaJapan”);

Table 7.4: Additional Methods of Locale Class

7.2.5 Language and Country Codes
The international standard defines the language and region codes. This standard assigns two- and threeletter codes to languages of the world. Similarly, two- and three-letter abbreviations are used for each
country or major region of the world. The Locale object uses the two-letter codes for these codes.
Table 7.5 lists a few of the examples for language codes.

Language
English
Arabic
German

Code
En
Ar
De

Table 7.5: Language Codes
Table 7.6 lists a few of the examples for country codes.

Concepts

Country
United States
Canada
France
Japan

Code
US
CA
FR
JP

Table 7.6: Country Codes

V 1.0 © Aptech Limited

7

Session

Internationalization

The elements such as date, time, currency, and numbers are country specific and dependent on the
country codes.
Example: French is used in both France and Canada. The locale designators such as fr_CA (Frenchspeaking Canada) and fr_FR (French-speaking France) denote the differences.

7.2.6 Enabled Script Support
A script is the writing form for a language. Languages may share a script or have unique scripts. Displaying
text in locale specific language is a multi-step process including selecting font, arranging text into
paragraphs and line, selecting and rendering glyphs.
Text components need to support multiple locales. AWT Components can render scripts supported by
the locale host. If the host system is localized to Arabic, then AWT will display Arabic text components.
The same AWT component cannot display the text in a script different from the localized host. JFC Swing
component supports multiple scripts because of their independence from the host platform and their
use of the Unicode Charset.
Text widgets support scripts from different locales. An AWT component supports scripts that the host
supports, whereas Java Foundation Classes/Swing (JFC/Swing) components supports multiple scripts due
to their platform independent and Unicode support feature.
Some of the scripts supported for text display are listed in table 7.7:

Writing System
Arabic
Chinese (simplified)
Chinese (traditional)
Hebrew
Japanese
Korean

Language Support
Arabic
Chinese
Chinese
Hebrew
Japanese
Korean

Table 7.7: Supported Scripts

7.2.7 Creating the ResourceBundle Class
The ResourceBundle class is used to retrieve locale-specific information from the properties file.

Localized or translated into different languages

Handled for multiple locales at the same time

Supported for more locales later

V 1.0 © Aptech Limited

Concepts

This information allows you to write applications that can be:

Session

7
Internationalization

7.2.8 Using the ResourceBundle Class
The ResourceBundle class has a static and final method called getBundle() which helps to retrieve
a ResourceBundle instance as the general syntax is as follows:

ResourceBundle getBundle(String Locale)

This method helps to retrieve locale-specific information from a given properties file and takes two
arguments, namely, a String object and an object of Locale class. The object of ResourceBundle class is initialized with a valid language and country matching the available properties file.
Syntax:
public static final ResourceBundle getBundle(String baseName, Locale locale)

where,
baseName: It is a string, which specifies the default properties file name. It is a fully qualified

class name.

locale: It is an object of a class Locale.
ResourceBundle: It is the return type, that is, this method returns a ResourceBundle.

Code Snippet 2 shows how to retrieve the locale-specific information from MessageBundle_fr_
FR.properties file.
Code Snippet 2:
String language = “fr”; String country = “FR”; Locale currentLocale;
ResourceBundle messages;
// Creates a
country

Locale object with the language

French

and

// France
currentLocale = new Locale(language, country);
// Retrieves the locale-specific information
messages = ResourceBundle.getBundle(“MessagesBundle”, currentLocale);

Concepts

7.2.9 Fetching the Text from ResourceBundle Class
To retrieve the locale-specific data from the properties file, you have to first create a ResourceBundle
class object. Once you have a ResourceBundle object, you invoke the methods listed in table 7.8.

Method

Description

public final String
The getString() method returns a string which represents the
getString(String key) value from the properties file associated with the key.

V 1.0 © Aptech Limited

7

Session

Internationalization

Method

public abstract
Enumeration<String>
getKeys()

Description
The getKeys() method returns an enumeration object
representing all the available keys in the properties file.
Table 7.8: Methods of ResourceBuilder

Code Snippet 3 shows how to retrieve individual locale-specific data.
Code Snippet 3:
// Creates a Locale object for the French language and France country
Locale currentLocale = new Locale(“fr”, “FR”);
// Creates a ResourceBundle object from a MessageBundle.properties fie
ResourceBundle messages = ResourceBundle.getBundle(“MessageBundle”,
currentLocale);
// Retrieves individual locale-specific data

String greeting = messages.getString(“greetings”);

String inquiry = messages.getString(“inquiry”);

String farewell = messages.getString(“farewell”);

Figure 7.4 show the output for Code Snippet 3.

Figure 7.4: Output - Retrieve Local-specific Information
Code Snippet 4 shows how to iterate through all the keys and retrieve their values.
Code Snippet 4:
while(bundleKeys.hasMoreElements()) {
String key = (String) bundleKeys.nextElement();
String value = messages.getString(key);
System.out.println(“key = “ + key + “, “ +“value = “ + value);
}

V 1.0 © Aptech Limited

Concepts

Enumeration bundleKeys = messages.getKeys();

Session

7
Internationalization

Figure 7.5 shows the output for Code Snippet 4.

Figure 7.5: Output – Iteration on Keys

7.2.10 Methods of ResourceBundle Class
The ResourceBundle class has methods which can be used for localization of an internationalized
application.
AdditIonla methods of the ResourceBundle are listed in table 7.9.

Method

Description

public Locale getLocale()

public final String[]
getStringArray(String key)

This method is normally invoked after the getBundle()
method is used to retrieve a resource bundle object to
check whether the locale object of the resource bundle
corresponds to the proper locale.
The static method getStringArray() is used to retrieve
a string array for the specified key from the resource bundle
or one of its parents.
Example:
// Retrieves the resource bundle for the

Concepts

// default
locale ResourceBundle messages =
ResourceBundle.getBundle(“MessagesBundle”);
String[] values = messages.getStringArray(“g
reetings”);

V 1.0 © Aptech Limited

7

Session

Internationalization

Method

protected void
setParent(ReourceBundle
parent)

Description
The static method setParent() is used to set the parent
bundle of a resource bundle object. The parent bundle is
searched for a particular resource, if the resource is not
found in the current resource bundle.
Example:
ResourceBundle messages; ResourceBundle
warnings;
// Retrieves the resource bundle for the
// messages
messages = ResourceBundle.getBundle(“Message
sBundle”);
// Retrieves the resource bundle for the //
warnings
warnings = ResourceBundle.getBundle(“Warning
sBundle”);
// Set the warnings bundle as the parent
messages.setParent(warnings);

Table 7.9: Additional Methods of ResourceBuilder
Code Snippet 5 shows how to retrieve the locale object of resource bundle.
Code Snippet 5:
String language = “fr”; String country = “FR”; Locale currentLocale;
ResourceBundle messages;
// Creates a Locale object with the language French and country France
currentLocale = new Locale(language, country);
...
...

// Retrieve the locale of the resource bundle Locale locale = messages.
getLocale();
// Check if the default locale corresponds to the French locale. if (currentLocale.
getCountry().equals(locale.getCountry) && currentLocale.getLanguage().
equals(locale.getLanguage) ) {
// The default locale corresponds to French locale

V 1.0 © Aptech Limited

Concepts

// Retrieves the resource bundle for the default locale messages = ResourceBundle.
getBundle(“MessagesBundle”);

Session

7
Internationalization

...
...
}

7.3 Internationalization Elements
Normally, the captions of a GUI component contain text which can be easily localized. However, these
captions may also contain elements such as date, numerals, percentage factor, and measurement and
so on. Since, such elements may vary with culture, region, and language, it is required to format the
captions of the GUI components.
Formatting the captions of the GUI components ensures that the look and feel of the application is in a
locale-sensitive manner. The code, which handles the GUI, is locale-independent, without the need to
write formatting routines for specific locales.

7.3.1 Need for Formatting
The format of numbers, currencies, and percentages vary with culture, region, and language. Hence, it
is necessary to format them before they are displayed. For example, the number 12345678 should be
formatted and displayed as 12,345,678 in the US and 12.345.678 in Germany.
Similarly, the currency symbols and methods of displaying the percentage factor also vary with region
and language.
Formatting is required to make an internationalized application independent of local conventions with
regards to decimal-point, thousands-separators, and percentage representation.

Concepts

Figure 7.6 displays the need for formatting.

Figure 7.6: Need for Formatting

V 1.0 © Aptech Limited

7

Session

Internationalization

7.3.2 Numbers, Currencies, and Percentages
The NumberFormat class is used to create locale-specific formats for the following as listed in table
7.10.

Type

Format

Numbers

getNumberInstance()

Currencies

getCurrencyInstance()

Percentages

getPercentInstance()

Description
The getNumberInstance() returns
an instance of a NumberFormat class
initialized to default or specified locale. You
then invoke the format() method of the
NumberFormat class. The number to be
formatted is passed as an argument. The
argument can be a primitive or a wrapper
class object.
The NumberFormat class has a static
method getCurrencyInstance()
which takes an instance of Locale class as
an argument. The getCurrencyInstance()
returns an instance of a NumberFormat
class initialized to the specified locale.
This class has a static method
getPercentInstance() which takes an
instance of Locale class as an argument.
The getPercentInstance() returns
an instance of a NumberFormat class
initialized to the specified locale.

Table 7.10: Methods of NumberFormat
Code Snippet 6 shows how to create locale-specific format of number for the country, France and
language, French.
Code Snippet 6:
NumberFormat numberFormatter;
String strAmount;
String strCurrency;
// Creates a Locale object with language as French and country
// as France
Locale locale = new Locale(“fr”, “FR”);
// Creates an object of a wrapper class Double
Double amount = new Double(123456.78);

V 1.0 © Aptech Limited

Concepts

String strPercent;

Session

7
Internationalization

// Retrieves the NumberFormatter instance
numberFormatter = NumberFormat.getNumberInstance(locale);
// Formats the number
strAmount = numberFormatter.format(amount);
// Retrieves the CurrencyFormatter instance
currencyFormatter = NumberFormat.getCurrencyInstance(locale);
// Formats the currency
strCurrency = currencyFormatter.format(currency);
// Retrieves the percentFormatter instance
percentFormatter = NumberFormat.getPercentInstance(locale);
// Formats the percent
strPercent = percentFormatter.format(percent);

7.3.3 Formatting Decimal Numbers Using DecimalFormat and
NumberFormat
Decimal numbers can be formatted using the DecimalFormat class. It is a subclass of the NumberFormat
class. It can format numbers in any locale. A DecimalFormat instance can be created for a specific
locale by creating an instance of NumberFormat and casting it to a DecimalFormat.
Code Snippet 7 shows how to create a DecimalFormat instance.
Code Snippet 7:
Locale locale = new Locale(“en”, “UK”);
String pattern = “###.##”;
DecimalFormat decimalFormat = (DecimalFormat)
NumberFormat.getNumberInstance(locale);
decimalFormat.applyPattern(pattern);
String format = decimalFormat.format(123456789.123);

Concepts

System.out.println(format);

The output of the program is: 123456789.12
Code Snippet 8 shows how to create a DecimalFormat instance in German.

V 1.0 © Aptech Limited

7

Session

Internationalization

Code Snippet 8:
Locale locale = new Locale(“de”, “Germany”);
String pattern = “###, ##”;
DecimalFormat decimalFormat = (DecimalFormat)
NumberFormat.getNumberInstance(locale);
decimalFormat.applyPattern(pattern);
String format = decimalFormat.format(123456789.123);
System.out.println(format);

The output of the program is: 123456789, 12
Note - The output shows the use of a comma instead of a dot to separate the integer part from the

fraction part of the number.

Different symbols can be used as a decimal separator using a DecimalFormatSymbols instance.
Code Snippet 9 shows how to use a DecimalFormatSymbols instance.
Code Snippet 9:
Locale locale = new Locale(“en”, “UK”);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
symbols.setDecimalSeparator(‘:’);
symbols.setGroupingSeparator(‘,’);
String pattern = “#,##0.###”;
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
String number = decimalFormat.format(987654321.321);
System.out.println(number);

The output of the program is: 987,654,321:321

The date and time format should conform to the conventions of the end user’s locale. The date and time
format varies with culture, region, and language. Hence, it is necessary to format them before they are
displayed.
For example, in German, the date can be represented as 20.04.07, whereas in US it is represented as
04/20/07. Java provides the java.text.DateFormat and java.text.SimpleDateFormat class to
format date and time.

V 1.0 © Aptech Limited

Concepts

7.3.4 Date and Time

Session

7
Internationalization

7.3.5 Benefits and Formatting Date and Time
The DateFormat class is used to create locale-specific formats for date. You then invoke the format()
method of the NumberFormat class. The number to be formatted is passed as an argument. The
argument can be a primitive data type or a wrapper class object.
Figure 7.7 displays the formatted date and time.

Figure 7.7: Formatted Date and Time
The method to get the formatted date is as follows:

DateFormat getDateInstance(style, locale)

This method returns an instance of the class DateFormat for the specified style and locale.
Syntax:
public static final DateFormat getDateInstance(int style, Locale locale)

where,
style: It is an integer and specifies the style of the date. Valid values include: DateFormat.LONG, DateFormat.SHORT, and DateFormat.MEDIUM
locale: It is an object of the Locale class and specifies the format of the locale.

Code Snippet 10 shows how to retrieve a DateFormat object.
Code Snippet 10:
Date today;

Concepts

String strDate;
DateFormat dateFormatter;
Locale locale = new Locale(“fr”, “FR”);
dateFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
today = new Date();
strDate = dateFormatter.format(today);
System.out.println(strDate);

V 1.0 © Aptech Limited

7

Session

Internationalization

7.3.6 DateFormat Class and its Methods
The DateFormat class has methods which can be used to format the date and time for a specific locale.
The following method of the DateFormat will be discussed in the session:

getDateTimeInstance()

The static method getDateTimeInstance() is used to retrieve a date and time formatter with
the default formatting style for the default locale.
Syntax:
public static final DateFormat getDateTimeInstance()

where,
DateFormat: It is an object of the DateFormat class with default style for default locale.
Code Snippet 11 shows how to retrieve a date and time formatter with default style for default locale.
Code Snippet 11:
Date today;
String strDate;
DateFormat dateFormatter;
dateFormatter = DateFormat.getDateTimeInstance();
today = new Date();
strDate = dateFormatter.format(today);
System.out.println(strDate);

The following is the syntax of overloaded method getDateTimeInstance().
Syntax:
public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle,
Locale locale)

where,

timeStyle: It is an int which specifies the time formatting style. Valid values include: DateFormat.
SHORT, DateFormat.MEDIUM, DateFormat.LONG, and DateFormat.FULL
locale: It is an object of the Locale class and specifies the current locale.
DateFormat: It is an object of the DateFormat class with specified style and locale.

V 1.0 © Aptech Limited

Concepts

dateStyle: It is an int which specifies the date formatting style. Valid values include: DateFormat.
SHORT, DateFormat.MEDIUM, DateFormat.LONG, and DateFormat.FULL

7

Session

Internationalization

Code Snippet 12 shows how to retrieve a date and time formatter with specified style and locale.
Code Snippet 12:
Date today;
String strDate;
DateFormat dateFormatter;
Locale locale = new Locale(“fr”, “FR”);
dateFormatter
= DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT, locale);
today = new Date();
strDate = dateFormatter.format(today); System.out.println(strDate);

7.3.7 SimpleDateFormat Class and its Methods
The SimpleDateFormat class is a concrete implementation of the abstract class, DateFormat. The
SimpleDateFormat class has methods to parse and convert a text to date.
The following method of the SimpleDateFormat is as follows:
parse(String text, ParsePosition pos)

The parse() method parses text from a string to produce a Date object. This method parses the text
from a given position specified by an object of the ParsePosition class. If parsing succeeds, the index
of the parse position is updated to the last character in the text where the date ends.
Syntax:
public Date parse(String text, ParsePosition pos)

where,
text: It is a String containing any text including a valid date.
pos: It is an object of the ParsePosition class which specifies the position in the text from where

to start parsing.

Code Snippet 13 shows how to parse a text and return a date.

Concepts

Code Snippet 13:
Date today; String text;
SimpleDateFormat dateFormat;
ParsePosition pos;
try {
// Assign text containing a valid date

V 1.0 © Aptech Limited

7

Session

Internationalization

text = “Today the date is 26/06/2007 and tomorrow…”;
// Create a SimpleDateFormat object with the pattern dd/mm/yy dateFormat = new
SimpleDateFormat(“dd/mm/yyyy”);
// Specify the position of the date in text, 18 in the above text pos = new
ParsePosition(18);
// Parse the text to return a date object today = dateFormat.parse(text, pos);
System.out.println(“Date : “ + today);
} catch (NullPointerException ex)
{ System.out.println(“Exception : could not parse the date.”);
}

Figure 7.8 shows the output for Code Snippet 13.

Figure 7.8: Output – Parse Text

7.3.8 Formatting Messages
Displaying messages such as status and error messages are an integral part of any software.
If the messages are predefined such as ‘Your License has expired’, they can be easily translated into
various languages. However, if the messages contain variable data, it is difficult to create grammatically
correct translations for all languages.
For example, consider the message in English: ‘On 06/03/2007 we detected 10 viruses’. In
French, it is translated as: ‘Sur 06/03/2007 nous avons détecté le virus 10’. In German,
it is translated as: ‘Auf 06/03/2007 ermittelten wir Virus 10’. The position of verbs and the
variable data varies in different languages.

Concepts

Figure 7.9 displays formatting of messages.

Figure 7.9: Formatting Messages

V 1.0 © Aptech Limited

Session

7
Internationalization

7.3.9 Need for MessageFormat Class
It is not always possible to create a grammatically correct sentence with concatenation of phrases and
variables. The approach of concatenation works fine in English, but it will not work for languages in
which the verb appears at the end of the sentence. If the word order in a message is hard-coded, you
will not be able to create grammatically correct translations for all languages. The solution is to use the
MessageFormat class to create a compound message.
Code Snippet 14 shows how to concatenate several elements of a message.
Code Snippet 14:
int num = 10;
Date date = new Date();
String text = messageBundle.getString(“On”)+date.toString()+ messageBundle.
getString(“we detected”) + numVirus + messageBundle.getString(“virus”);

7.3.10 MessageFormat Class
To use the MessageFormat class, you typically perform steps listed in table 7.11.

Step

Description

Identify the variables in the message
Create a template

Create an Object array for variable
arguments

Concepts

Create a MessageFormat instance

The first step involves writing down the message and
identifying all the variable parts of the message.
A template is a string, which contains the fixed part
of the message and the variable parts. The variable
parts are encoded in {} with an argument number, for
example, {0}, {1}, and so on. Each argument number
should match with an index of an element in an
Object array containing argument values.
For each variable part in the template, a value is
required to be replaced. These values are initialized
in an Object array. The elements in the Object
array can be constructed using the constructors. If an
element in the array needs to be translated, it should
be fetched from the ResourceBundle with the
getString() method.
The next step is to create a MessageFormat
instance and set the desired locale. The locale is
important because the message may contain date
and numeric values, which are required to be
translated.

V 1.0 © Aptech Limited

7

Session

Internationalization

Step

Description

Apply and format the pattern

To apply the pattern, first, fetch the pattern string
from the ResourceBundle with the getString()
method. The MessageFormat class has a method
applyPattern() to the apply the pattern to the
MessageFormat instance. Once the pattern is
applied to the MessageFormat instance, you invoke
the format() method.

Table 7.11: Steps to Use MessageFormat Class

7.3.11 Procedure to Use MessageFormat Class
Let us understand how to use MessageFormat class with an example.
1.

First step involves creating a template for the following text.
At 6:41 PM, on April 25, 2007, we detected 7 viruses on the disk D.
The template for the message is as follows:
template = At {2,time,short} on {2,date,long}, we detected {1,number,integer}
virus on the disk {0}

where,
{2,time,short} indicates that the third element from the Object[] will replace this

variable part. This variable part is qualified to display the date in short style, it will display
only the time 6:41 PM.
{2,date,long} indicates that the third element from the Object[] will replace this vari-

able part. This variable part is qualified to display the date in long style, it will display date
in the format Month dd, yyyy, for example, April 25, 2007.
{1,number,integer} indicates that the second argument from the Object[] array will

replace the variable part. This variable part is qualified to display a number as an integer.

{0} indicates that the first element from the Object[] will replace this variable part. This

variable will be simply replaced without qualification.
2.

The second step involves creating an array of objects containing variable arguments.

Code Snippet 15:
template = At {2,time,short} on {2,date,long}, we detected {1,number,integer}
virus on the disk {0} Object[] messageArguments = {messages.getString(“disk”),
new Integer(7),new Date() };

V 1.0 © Aptech Limited

Concepts

Code Snippet 15 creates an Object array for the template.

Session
3.

7
Internationalization

The third step is to create an instance of MessageFormat class.
The following code creates an object of MessageFormat class.
MessageFormat formatter = new MessageFormat(“”);

4.

The last step is to format the text using MessageFormat instance.
Code Snippet 16 shows the complete code required to successfully translate the following message:
At 10:53 AM on April 26, 2007, we detected 7 viruses on the disk D:

Code Snippet 16:
Object[] messageArguments = {messages.getString(“disk”), new Integer(7), new
Date();
ResourceBundle messages = ResourceBundle.getBundle(“MessageFormatBundle”,
currentLocale);
MessageFormat formatter = new MessageFormat(“”); formatter.setLocale(currentLo
cale); formatter.applyPattern(messages.getString(“template”));
String output = formatter.format(messageArguments);
System.out.println(output);

The descriptions of the properties file used in the code are listed in table 7.12.

Method

MessageFormatBundle.properties

Description
disk = D:
template = At {2,time,short} on {2,date,long},
we detected {1,number,integer} virus on the disk {0}
template = À {2,time,short} {2,date,long}, nous avons
détecté le virus {1,number,integer} sur le disque {0}

MessageFormatBundle _ fr _
FR.properties disk = D
MessageFormatBundle _ de _
DE.properties disk = D

template = Um {2,time,short} an
{2,date,long}, ermittelten wir Virus
{1,number,integer} auf der Scheibe {0}

Table 7.12: Properties File

Concepts

7.3.12 ParsePosition Class
The ParsePosition class is used to specify the initial position from where to start parsing. The ParsePosition
has one constructor which takes an argument specifying the initial position to start parsing.
Syntax:
public ParsePosition(int initialPosition)

V 1.0 © Aptech Limited

7

Session

Internationalization

where,
initialPosition: Is an integer which specifies the initial position to start the parsing.

Code Snippet 17 shows how to specify the initial position for parsing the text.
Code Snippet 17:
ParsePosition pos;
...
// Start the parsing at zero position

Concepts

pos = new ParsePosition(0);

V 1.0 © Aptech Limited

Session

7
Internationalization

7.4 Check Your Progress
1.

Which of the following statements about Internationalization are true?
A.
B.
C.
D.
E.

Internationalized software is developed separately for each country and language.
Successful translation of the source files in the desired language is very difficult.
Cost of development of the product in the desired language will be much lower than
the one time cost.
Internationalized software should be developed such that it can be adapted without
engineering changes.
Internationalization is the process of designing an application, so that it can adapt to
various regions.

(A) A, B, and E
(B) A, C, and D
2.

E.

The translation of text is the least time-consuming part of the localization process.
Localization is the process of adapting software for a specific region.
Textual elements are stored outside the source code and retrieved dynamically.
Textual elements such as labels and messages for GUI components are hard-coded in
the program.
Support for new languages requires recompilation.

(A) B and E
(B) D and E

Concepts

B, D, and E
B, C, and E

Which of the following statements about Localization and its benefits are true?
A.
B.
C.
D.

3.

(C)
(D)

(C)
(D)

B and C
C and D

Which of the following statements about Unicode are true?
A. It is not possible to use the String class to convert standard encoding systems to and
from the Unicode system.
B. Unicode is a 32-bit character encoding system.
C. Unicode provides a unique number for every character irrespective of platform,
program, or language.
D. The Java platform does not use Unicode as its native character encoding.
E. The primitive data type char in Java is based on Unicode encoding.
(A) A and E
(B) D and E

(C)
(D)

B and D
C and E

V 1.0 © Aptech Limited

7

Session
4.

Internationalization

Which of the following statements about properties file and locales are true?
A. A properties file contains the information that is already translated into an
Internationalized program.
B. We do not need to create a properties file with the naming convention for every
country.
C. A Locale is an identifier for a particular combination of language and region.
D. To create a properties file you can use any plain text editor including Notepad.
E. We need not include ’.properties’ as an extension for property files.
(A) A, B, and E
(B) C and E

5.

(C)
(D)

A, B, and D
C and D

You are trying to retrieve the locale-specific information from the file MessageBundle _ fr _
FR.properties. Which of the options will help you to achieve this?
A. String language = “fr”; String country = “FR”; locale currentLocale;
ResourceBundle messages;

currentLocale = new locale(language, country);

B.

messages=ResourceBundle.getBundle(“MessagesBundle”,
currentLocale);
String language = “fr”; String country = “FR”; Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(country, language);

C.

messages=ResourceBundle.getBundle(“MessagesBundle”,
currentLocale);
String language = “fr”; String country = “FR”; Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(language, country);

D.

messages = ResourceBundle.getBundle(“MessagesBundle”,
currentLocale);
String language = “fr”;
Locale currentLocale; ResourceBundle messages;
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle(currentLocale,
”MessagesBundle”);

V 1.0 © Aptech Limited

Concepts

String country = “FR”;

Session
6.

7
Internationalization

You need to iterate through all the keys and retrieve their values. Which of the options will help you
to achieve this?
A.

Enumeration bundleKeys = messages.getKeys();
while(bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = messages.getString();

B.

System.out.println(“key = “ + key + “, “ + “value = “ + value);
Enumeration bundleKeys = messages.getKeys();
while(bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = messages.getString(key);

C.

System.out.println(“key = “ + key + “, “ + “value = “ + value);
Enumeration bundleKeys = messages.getKeys();
while(bundleKeys.hasMoreElements()) {
String key = bundleKeys.nextElement();
String value = messages.getString(key);

D.

System.out.println(“key = “ + key + “, “ + “value = “ + value);
Enumeration bundleKeys;
while(bundleKeys.hasMoreElements()) {
String key = bundleKeys.nextElement();
String value = messages.getString(key);
System.out.println(“key = “ + key + “, “ + “value = “ + value);

7.

Which of the following statements about component captions, numbers, currencies, percentages,
dates, and time are true?

Concepts

A.
B.
C.
D.
E.

The getCurrencyInstance() returns an instance of a NumberFormat class
initialized to the specified locale.
The argument passed can only be primitive data type.
The getCurrencyInstance() takes an instance of Locale class as an argument.
The date and time format need not conform to the conventions of the end user’s
Locale.
Formatting the captions of the GUI components ensures that the look and feel of the
application is in a locale-sensitive manner.

V 1.0 © Aptech Limited

7

Session

Internationalization

(A) A, C, D, and E
(B) B, C, D, and E
8.

(C)
(D)

A and D
C and D

Which of the following statements about Messages are true?
A. Once the pattern is applied to the MessageFormat instance, you invoke the
getString()method.
B. The MessageFormat class can be used to create a compound message.
C. The applyPattern() method is used to fetch an element from the
ResourceBundle.
D. A template is a string, which contains only the fixed part of the message.
E. The date and numeric values contained in a message need not be translated.
(C)
(D)

B and D
C and D

Concepts

(A) B
(B) A and E

V 1.0 © Aptech Limited

Session

7
Internationalization

7.4.1 Answers
B
C
D
D
C
C
A
A

Concepts

1.
2.
3.
4.
5.
6.
7.
8.

V 1.0 © Aptech Limited

7

Session

Internationalization

Summary
Internationalization is a way of designing an application, which adapts to various countries,
languages, and regions.

Such software is developed independent of the countries or language of its users, and then
localized for multiple languages.

Internationalization process involves creating a properties file to store locale-specific data and
defining a Locale for a country.

We then, create a ResourceBundle and use it to retrieve locale-specific information from the
properties file.

The GUI component captions contain text, which can be easily localized. However, these captions
may also contain elements such as date, numerals, percentage factor, measurements, and so on.

Since, these elements may vary with culture, region, and language, it is required to format the
captions of GUI components.

Concepts

V 1.0 © Aptech Limited

Internationalization

Concepts

Session

7

V 1.0 © Aptech Limited

Session 8
Networking
Welcome to the Session, Networking.
This session provides a brief introduction to networking in Java. This
session introduces the URL and URLConnection classes. The session
covers guaranteed communication with socket programming and use of
datagram packets for non-guaranteed communications. The session also
highlights the concept of network interface and cookie management in
HTTP connections.
In this Session, you will learn to:

Explain the basic concept of networking

Explain communicatio using Transmission Control Protocol
(TCP)

Explain URLConnection class

Explain Socket and ServerSocket class

Explain Datagram

Explain Network Interface

Explain Cookie

Session

8
Networking

8.1 Overview of Networking
Networking refers to the concept of various systems working together across a network. Programming
at the application layer allows this communication over a network. The java.net contains a collection of
classes and interfaces that support communication, allowing the users to focus on problem solving rather
than networking.
Java.net supports two common network protocols. These are the Transmission Control Protocol or

TCP and the User Datagram Protocol or UDP.

8.1.1 Introduction to Networking
Transmission Control Protocol (TCP) is a connection-based protocol that provides a reliable transmission
of data between two computers. On the Internet, computers communicate with each other using either
the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP). TCP is based on a fourlayered model.
Table 8.1 lists the various TCP layers.

Layer

Name

Functionality

Description

IV

Application

HTTP, FTP

In this layer, ‘high level’
protocols such as File
Transfer Protocol (FTP) and
Hypertext Transfer Protocol
(HTTP) operate.

III

Transport

TCP, UDP(User
Datagram Protocol)

This layer deals with opening
and maintaining connections,
and ensures that packets are
transmitted and received.

II

Network

IP

This layer defines Internet
Protocol (IP) addresses,
and deals with packet
transmission from one IP
address to another.

I

Link

IP

This layer describes the
physical equipment required
for communications, such as
twisted pair cables.

Concepts

Table 8.1: TCP Layers

8.1.2 Communication on Computers
Two applications on remote machines can have reliable communication when they establish a connection.
Once the connection is established, the applications can send data back and forth over that connection.
TCP guarantees that data sent from one end of the connection is received at the other end. It also
guarantees that the data received is in the same order as it was sent.

V 1.0 © Aptech Limited

8

Session

Networking

Figure 8.1 displays the communication between computers.

Figure 8.1: Communication between Computers

8.1.3 Transmission Control Protocol (TCP)
TCP provides a point-to-point channel for applications that require reliable connections. HTTP, FTP and
Telnet are examples of applications that require reliable connections. Typically, you do not write programs
at the lower level like transport, instead you generally program at the application level. Java provides the
java.net package which contains all the necessary classes to perform system-independent network
communications.

8.1.4 User Datagram Protocol (UDP)
A User Datagram Protocol (UDP) is a connectionless protocol. A connection between the sender and
the receiver is not established before communication. A single socket connection can be used to send
messages to multiple servers. The message is a datagram of fixed length termed as a record.

A computer generally has a single physical connection available for the network. The physical connections
are the two serial ports COM1 and COM2. One of these is usually used by a pointing device such as the
mouse. That leaves only a single physical connection for the network. Several applications running on a
machine need to use this single physical connection for communication.
If data arrives at these physical connections, there is no means to identify the application to which it
should be forwarded. Hence, data being sent and received on the physical connection are based on the
concept of ports.

V 1.0 © Aptech Limited

Concepts

8.1.5 Networking Basics

Session

8
Networking

8.1.6 Concept of a Port
The physical connection is logically numbered within a range of 0 to 65535. They are called as Ports. The
port numbers ranging from 0 to 1023 are reserved. They are reserved for use by well-known services
such as HTTP, FTP and other system services. These ports are called well-known ports. Your applications
should not use any of the port numbers in this range.
Data transmitted over the Internet is accompanied with the destination address and the port number.
The destination address identifies the computer, and the port number identifies the application.
Figure 8.2 displays the port.

Figure 8.2: Port

8.2 URL

Concepts

URL or Uniform Resource Locator is a formatted text string used to identify a resource on the Internet.
Simply out a URL can be thought of as a file name on the World Wide Web, but they also point to other
resources on the network like databases and command outputs.
Any URL is made up of three substrings: the network protocol, the host name or address, and the file or
resource location. Let us now learn how URLs are created and use in Java Swing application.

8.2.1 Introduction to URL
URL is an acronym for Uniform Resource Locator. It is a reference or an address to a resource on the
Internet. The resource can be an HTML page, an image or simply any file. You provide a URL to your Web
browser so that it can locate the resource on the Internet.

V 1.0 © Aptech Limited

8

Session

Networking

The concept of URL is similar to an address on a letter. The address is used by the post office to locate
your house.
A URL is a string that takes the form protocol://resource. It has two main parts:

Protocol Identifier
The protocol identifier is the name of the protocol, which is used to fetch the resource from the
Internet. Several protocols are available to access different types of resources like Hypertext
Transfer Protocol (HTTP), File Transfer Protocol (FTP), Gopher, File and
News.

Resource Name
The resource name includes the complete address of the resource. The format of the resource
name depends on the protocol being used. The resource name is separated from the protocol identifier with a colon and two forward slashes.

8.2.2 Components of URL
The resource name contains one or more components which are listed in table 8.2.

Component

Description

Host Name

The name of the machine where the resource resides

File Name

The path to the file on the host

Port Number

The port number to which to connect (optional)

Table 8.2: Components of URL

8.2.3 Retrieve a Resource
To retrieve a resource index.html on a host www.yahoo.com using port number 80, the URL would be
as follows: http://www.yahoo.com:80/index.html
Since the port number is optional the mentioned URL can be specified as follows:
http://www.yahoo.com/index.html

Concepts

Since the file name index.html is the default for most Web sites on the Internet, the URL can be further
simplified as: http://www.yahoo.com

V 1.0 © Aptech Limited

Session

8
Networking

Figure 8.3 displays the address to retrieve a resource.

Figure 8.3: Retrieving a Resource

8.2.4 Creating a URL
The java.net package has a class URL which can be used to construct an URL object. The URL class has
several constructors, all of which throw a MalformedURLException if no protocol is specified, or an
unknown protocol is found.
An instance of URL class is created using one of the constructors listed in table 8.3.

Component

URL(String url)

URL(String protocol,
String host, String file)

Concepts

URL(String protocol,
String host, int port,
String file)
URL(URL baseURL, String
relativeURL)

Description
Constructs an absolute URL object with the specified string
representing a valid URL.
Constructs an absolute URL object with the specified protocol,
host, and the resource file.
Constructs an absolute URL object with the specified protocol,
host, port, and the resource file.
The first argument specifies the base of the new URL. The
second argument specifies the rest of the resource name
relative to the base as a string. If baseURL is null, then
relativeURL is treated like an absolute URL. If relativeURL is
an absolute URL specification, then the constructor ignores
baseURL.
Table 8.3: URL Constructors

V 1.0 © Aptech Limited

8

Session

Networking

URL(String url)

Code Snippet 1 shows how to create URL object with the specified String representing a valid URL.
Code Snippet 1:
try {
URL url = new URL(“http://www.yahoo.com/index.html”);
} catch(MalformedURLException e) { System.out.println(“Exception : “ +
e.getMessage());
}

URL(String protocol, String host, String file)

Code Snippet 2 shows how to create URL object with http as the protocol, www.yahoo.com as
the host and index.html as the resource file.
Code Snippet 2:
try {
URL url = new URL(“http”, “www.yahoo.com”, “index.html”);
} catch(MalformedURLException e) { System.out.println(“Exception : “ +
e.getMessage()); }

URL(String protocol, String host, int port, String file)

Code Snippet 3 shows how to create an URL object with http as the protocol, www.yahoo.com as
the host, 80 as the port and index.html as the resource file.
Code Snippet 3:
try
{
URL url = new URL(“http”,“www.yahoo.com”,80,“index.html”);
}catch(MalformedURLException e)
{

Concepts

System.out.println(“Exception : “ + e.getMessage());

V 1.0 © Aptech Limited

8

Session

Networking

URL(URL,String)

Code Snippet 4 shows how to create a base URL and a relative URL from the base.
Code Snippet 4:
try {
URL baseURL = new URL(“http://www.yahoo.com” ); URL url = new
URL(baseURL, “index.html”);
} catch(MalformedURLException e) { System.out.println(“Exception : “ +
e.getMessage());
}

8.2.5 Methods of URL Class
The URL class has some important methods as listed in table 8.4.

Methods

public String
getHost()
public String
getFile()
public String
getPath()
public final
InputStream
openStream()

Concepts

public String
getQuery()

public final
Object
getContent()
public int
getDefaultPort()
public String
getProtocol()

Description
This method returns the host name of the URL. This method
returns the IP address enclosed in square brackets.
This method returns the file name of the URL. If the URL has a
query string attached, then the query string is also concatenated
and returned.
This method returns only the path of the URL. If the URL has a
query string, they are not returned.
Opens a connection to a URL and returns an InputStream for
reading from that connection. The InputStream returned can
be wrapped within a BufferedReader to read directly from the
URL.
The getQuery() method is used to retrieve the query part of
the URL. A “?” delimits the URL and the query part. The query
part contains name=value, pair, multiple pairs are delimited with
the ‘&’ sign.
The getContent() method is used to retrieve the contents of
the URL.
The getDefaultPort() method is used to retrieve the default
port associated with the given URL.
The getProtocol() method is used to retrieve the protocol
name of the URL.
Table 8.4: Methods of URL

V 1.0 © Aptech Limited

8

Session

Networking

public String getHost()

Code Snippet 5 shows how to retrieve host name of a URL.
Code Snippet 5:
String strHostName; URL url;
try
{// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/index.
html”);
// Retrieves the host name of the URL strHostName =url.getHost();
System.out.println(“Host : “ + strHostName);
}
catch(MalformedURLException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

public String getFile()

Code Snippet 6 shows how to retrieve file name of a URL.
Code Snippet 6:
String [] URL url;
try
{// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/
index.html”);
// Retrieves the file name of the URL
String strPath =url.getFile();
}catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}

V 1.0 © Aptech Limited

Concepts

System.out.println(“File Name : “ + strFile);

8

Session

Networking

public String getPath()

Code Snippet 7 shows how to retrieve the path of a URL.
Code Snippet 7:
String strPath; URL url;
try
{// Creates and instantiates URL object
URL url = new
index. html”);

URL(“http://java.sun.com/docs/books/tutorial/

// Retrieves the path name of the URL strPath =url.getPath();
System.out.println(“Path : “ + strPath);
}catch(MalformedURLException ex)
{System.out.println(“Exception : “ + ex.getMessage());
}

public final InputStream openStream()

Code Snippet 8 shows how to open a connection to a URL and read the contents from that URL.
Code Snippet 8:
try
{String strText;
// Creates and instantiates URL object URL url = new URL(“http://java.sun.
com”);
// Wraps the InputStreamReader into BufferedReader object BufferedReader
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
// Reads the contents from the URL
while ((strText = reader.readLine()) != null) System.out.
println(strText);

Concepts

// Closes the BufferedReader reader.close();
catch(MalformedURLException ex)
{System.out.println(“Exception : “ + ex.getMessage());
}}

V 1.0 © Aptech Limited

8

Session

Networking

public String getPath()

Code Snippet 9 shows how to retrieve the query part of an URL.
Code Snippet 9:
String strQuery; try {
// Creates and instantiates URL object
URL url = new URL(“http://www.bookpool.com/ss?qs=Java+Complete+
Reference”);
// Retrieve the query from the URL strQuery =

url.getQuery();

System.out.println(“Query : “ + strQuery);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}

public final Object getContent()

Code Snippet 10 snippet shows how to retrieve the default port number of the URL.
Code Snippet 10:
int port; try {
// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/index.
html”);
// Retrieve the default port number of the URL port =
getDefaultPort();

url.

System.out.println(“Default Port number : “ + port);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());

Concepts

}

V 1.0 © Aptech Limited

8

Session

Networking

public String getProtocol()

Code Snippet 11 shows how to retrieve the protocol name of the URL.
Code Snippet 11:
String strProtocol; try {
// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/ index.
html”);
// Retrieve the protocol name of the URL strProtocol = url.getProtocol();
System.out.println(“Protocol : “ + strProtocol);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}

8.2.6 Methods of InetAddress Class
The InetAddress class is used to create an IP address. An IP address is either a 32 bit or 128 bit unsigned
number used by IP which is a low level protocol. The InetAddress class is used for encapsulating the
numerical IP address and the domain name for that address. The class offers numerous methods for
dealing with hostnames and IP address.
One of the factory methods are used to create an instance of InetAddress class as there are no visible
constructors in this class. Factory methods are static methods in a class that returns an instance of that
class. To create an instance of InetAddress class, the three factory methods are: getLocalHost(),
getByName() and getAllByName().

The InetAddress class has the methods listed in table 8.5.

Concepts

Method

public String
getHostAddress()
public String
getHostName()
public static
InetAddress
getLocalHost()
public static
InetAddress
getByName(String
host)

Description
This method returns the raw IP address in textual format.
This method returns the host name of the IP address.
This method returns an IP address of the local host.
This method returns an IP address of the specified host name. The
host name can either be a machine name, such as “java.sun.com”,
or a textual representation of its IP address. If the specified host
is a literal IP, only the validity of the address format is checked.

V 1.0 © Aptech Limited

8

Session

Networking

Method

Static
InetAddress[]
getAllByName
(String name)

Description
The getAllByName() method returns an array of InetAddress.
The array represents all of the addresses that a particular name
resolves. The method. will throw an UnknownHostException if it
cannot resolve the name to at least one address.
Table 8.5: Methods of InetAddress Class

public String getHostAddress()

Code Snippet 12 shows how to retrieve the string representation of an IP address.
Code Snippet 12:
InetAddress address = null;
// Retrieves the local host address try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException ex) { ex.printStackTrace();
}// Retrieves the string representation of the local host address String
strAddress = address.getHostAddress();

public String getHostName()

Code Snippet 13 shows how to retrieve the textual name of host.
Code Snippet 13:
InetAddress address = null;
// Retrieves the local host address try {
address = InetAddress.getLocalHost();
catch (UnknownHostException ex) { ex.printStackTrace();
}
// Retrieves the textual name of the local host String strAddress =
address.getHostName();
public static InetAddress getLocalHost()

Code Snippet 14 shows how to retrieve the InetAddress of local host.
Code Snippet 14:
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException ex) { ex.printStackTrace();

V 1.0 © Aptech Limited

Concepts

8

Session

Networking

public static InetAddress getByName (String host)

Code Snippet 15 shows how to retrieve the IP address of a given host.
Code Snippet 15:
InetAddress address = null; try {
address = InetAddress.getByName(“www.yahoo.com”);
} catch (UnknownHostException ex) { ex.printStackTrace();
}

Static InetAddress[] getAllByName (String name)

Code Snippet 16 shows the use of this method.
Code Snippet 16:
try
{
InetAddress address = InetAddress.getByName (args[0]); System.out.
println (“Address: “ + args[0] + “ = “ + address);
InetAddress[] add = InetAddress.getAllByName(args[0]); for(int i = 0; i <
add.length; i++) {
System.out.println (“Name of = “ + add[i] );
}
. . .}
} catch(UnknownHostException e) {
System.out.println (“Unable to translate the address.” + e);
}

8.3 URLConnection Class

Concepts

The URLConnection class lets users to perform actions such as reading from or writing to a connection.
After creating an URL, the URL object is called using the openConnection() method. A new
URLConnection object is created every time this method is called.
Most operations like getInputstream and getOutputStream will implicitly call the URLConnection
object. Other operations need the openConnection method to get connected.

8.3.1 URLConnection
URLConnection is an abstract class that represents the communication link between an application

and a URL. Instances of this class can be used to read from and to write to the resource referenced by
V 1.0 © Aptech Limited

8

Session

Networking

the URL.
You cannot instantiate an URLConnection object directly; a valid URL instance is required to create an
instance of URLConnection from the URL. An instance of URLConnection class can be used to:

Inspect and set the properties of connection

Obtain information such as content length, content type, and so on from the URL

Move data through the connection by obtaining an instance of the input and output streams

8.3.2 Open Connection() Method
The URL class has a method openConnection() to create an URLConnection instance. To communicate
with a URL with the openConnection() method, you perform the steps listed in table 8.6.

Steps

Description

Use the

openConnection()
method
Retrieve the

InputStream from
the connection
Retrieve the

OutputStream from
the connection

If the openConnection() method of the URL class is executed
successfully, a reference to the URLConnection object is returned.
If the openConnection() method fails to execute, an IOException
is raised.
The InputStream object is retrieved from the URLConnection
object. This object is wrapped within a BufferedReader object to
read directly from the URL.
The OuputStream object is retrieved from the URLConnection
object. This object is wrapped within a BufferedWriter object to
write directly to the URL.

Table 8.6: Steps to Communicate with the URL

openConnection()

Code Snippet 17 shows how to use the openConnection() method of the URL class.
Code Snippet 17:
url = new URL(“http://www.yahoo.com/”); URLConnection urlCon = url.
openConnection();
} catch (MalformedURLException ex) { ex.printStackTrace();
} catch (IOException ex) { ex.printStackTrace();
}

V 1.0 © Aptech Limited

Concepts

URL url = null; try {

8

Session

Networking

openConnection()

Code Snippet 18 shows how to retrieve the InputStream from an instance named urlCon of class
URLConnection and wrap it within a BufferedReader object.
Code Snippet 18:
try {
}
InputStream in = urlCon.getInputStream(); BufferedReader reader = new
BufferedReader(new InputStreamReader(in));
catch (IOException ex) {
ex.printStackTrace();

OutputStream()

Code Snippet 19 displays how to retrieve the OutputStream from an instance named urlCon of
class URLConnection and wrap it within a BufferedWriter objects.
Code Snippet 19:
try {
OutputStream out = urlCon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)
);
} catch (IOException ex) { ex.printStackTrace();
}

8.3.3 Methods of URLConnection Class
The methods of the URLConnection class are listed in table 8.7.

Method

Concepts

public
getContentType()

Description

The getContentType() method is used to retrieve the content
type of the resource that the URL references. The method will
return null if it is not known.
public
The getContentLength() method is used to retrieve the content
getContentLength() length of the resource that is referenced by the URL connection.
The method will return -1 if the content length is not known.
public
The getConnectTimeout() method is used to retrieve the settings
getConnectTimeout() of the connection timeout of the URL in milliseconds. If the setting
is disabled then a value of 0 is returned, which indicates that the
timeout is infinity.

V 1.0 © Aptech Limited

8

Session

Networking

Method

Description

public
The setConnectTimeout() method is used to set a specified
setConnectTimeout() timeout value in milliseconds. The timeout value is used when

opening a communication link to the resource referenced by
the URLConnection. An exception, SocketTimeOutException,
is raised when the timeout value expires before a connection
can be established. A timeout value of zero indicates an infinite
timeout.

Table 8.7: Methods of URLConnectors

getContentType()

Code Snippet 20 shows how to retrieve the content type of the URL resource.
Code Snippet 20:
String strContentType; try {
// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/index.
html”);
URLConnection urlCon = url.openConnection();
// Retrieve the content type of the URL strContentType =
getContentType();

urlCon.

System.out.println(“Content Type : “ + strContentType);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}

public getContentLength()

Code Snippet 21 shows how to retrieve the content length of the URL resource.
Code Snippet 21:
...
// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/index.
html”);
URLConnection urlCon = url.openConnection();

V 1.0 © Aptech Limited

Concepts

int contentLength; try {

8

Session

Networking
// Retrieve the content length of the URL resource contentLength = urlCon.
getContentLength();
System.out.println(“Content Length: “ + contentLength);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}

public getConnectTimeout()

Code Snippet 22 shows how to retrieve the connection timeout of the URL.
Code Snippet 22:
...
int contentLength; try {
// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/index.
html”);
URLConnection urlCon = url.openConnection();
// Retrieve the content length of the URL resource contentLength = urlCon.
getContentLength();
System.out.println(“Content Length: “ + contentLength);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}
...

public setConnectTimeout()

Code Snippet 23 shows how to set the connection timeout of the URL.
Code Snippet 23:

Concepts

int timeOut; try {
// Creates and instantiates URL object
URL url = new URL(“http://java.sun.com/docs/books/tutorial/index.
html”);
URLConnection urlCon = url.openConnection();
// Assign a timeout value of 30 seconds timeOut = 30000;

V 1.0 © Aptech Limited

8

Session

Networking

// Sets the connection timeout of the URL urlCon.setConnectTimeout(timeO
ut);
System.out.println(“Connection timeout set to : “ + timeOut+“
milliseconds”);
} catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
}
...

8.4 Socket Class
The Socket class provides a way for two computers to communicate with each other through the network.
This happens using the TCP protocol. The client’s program creates a socket and attempts to connect it to
the server. After the connection is set up, the server creates a socket object. Communication occurs by
writing to and reading from the socket.

8.4.1 What is a Socket?
A socket is one end-point of a two-way communication link between two programs running on the
network. A server application runs on a particular machine and has a socket bound to a specific port
number. The server then waits, listening to a client socket to make a connection request.
On the client-side, the client application needs to know the host name of the machine on which the
server application is running and the port number on which the server is listening. To make a connection
request, the client opens a socket with the server on the server’s machine and port.
Figure 8.4 displays a socket.

8.4.2 Creating a Socket
The java.net.Socket class is used to represent the connection between a client program and a server
program. The Socket class represents the client side of the connection. The Socket class has several
constructors to create a socket.

V 1.0 © Aptech Limited

Concepts

Figure 8.4: Socket

8

Session

Networking

Following is most often used constructor to create a socket:

Socket(String host, int port);

Constructs a socket with the IP address specified by variable host, to send client requests on the
port specified by variable port. If the host does not exist, this constructor throws an UnknownHostException. If an error occurs when creating a socket, an IOException is thrown.
Syntax:
Socket(String host, int port) throws UnknownHostException, IOException

where,
host: is a string which represents the IP Address of the host.
port: is an integer representing the port number on which the host is listening.

Code snippet 24 shows how to create a socket on local host machine at port number 5000.
Code Snippet 24:
Socket socket; String host;
final int PORT = 5000; host = “localhost”; try {
socket = new Socket(host, PORT);
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

Concepts

Figure 8.5 displays the socket creation.

Figure 8.5: Socket Creation
V 1.0 © Aptech Limited

8

Session

Networking

8.4.3 Reading from and Writing to a Socket
Once a Socket instance is created successfully perform the following steps to use the socket:
Table 8.8 lists the steps to use socket.

Steps
Retrieve the

InputStream from the
socket

Retrieve the

OutputStream from
the socket

Read from the

InputStream
Write to the
OutputStream

Description
The Socket class has a method getInputStream() which returns an
InputStream object associated with a host’s socket. This object is
normally wrapped in a BufferedReader object, for directly reading
data from the socket.
The Socket class has a method getOutputStream() which returns
an OutputStream object associated with a host’s socket. This
object is normally wrapped in a PrintStream or PrintWriter object
for writing data to the socket.
Once a BufferedReader object is created, you use the readLine()
method to read from the socket until a null is encountered which
indicates that all data sent from the host has been read.
Once a PrintStream or PrintWriter object is created, you use the
println() method to write data to the host.
Table 8.8: Socket Constructors

getInputstream()

Code Snippet 25 shows how to retrieve the InputStream of a socket.
Code Snippet 25:
Socket socket; String host;
final int PORT = 5000; BufferedReader reader; try {
host = “localhost”;
// Creates a Socket object socket = new Socket(host, PORT);
// Retrieves the input stream of the socket reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException ex) {
} catch (IOException ex) { ex.printStackTrace();
}

V 1.0 © Aptech Limited

Concepts

} catch (UnknownHostException ex) { ex.printStackTrace();

Session

8
Networking

getOutputStream()

Code Snippet 26 shows how to retrieve the OutputStream of the socket.
Code Snippet 26:
Socket socket; String host;
final int PORT = 5000; PrintWriter writer; host = “localhost”; try {
// Creates a Socket object socket = new Socket(host, PORT);
// Retrieves the output stream of the socket writer = new PrintWriter(socket.
getOutputStream());
} catch (UnknownHostException ex) { ex.printStackTrace();
} catch (IOException ex) { ex.printStackTrace();}

readLine()

Code Snippet 27 shows how to read from a socket.
Code Snippet 27:
Socket socket;
String host = “localhost”; String strInfo = “”;
inal int PORT = 5000; BufferedReader reader; try {
// Creates a Socket object socket = new Socket(host, PORT);
// Retrieves the input stream of the socket Socket socket;
String host = “localhost”; String strInfo = “”;
inal int PORT = 5000; BufferedReader reader; try {
// Creates a Socket object socket = new Socket(host, PORT);
// Retrieves the input stream of the socket
Reader = new BufferedReader(new InputStreamReader(socket.
getInputStream()));
// Reads from a socket

Concepts

while((strInfo = reader.readLine()) != null) {
reader = new BufferedReader(new InputStreamReader(socket.
getInputStream()));
// Reads from a socket
reader = new BufferedReader(new InputStreamReader(socket.
getInputStream()));
// Reads from a socket

V 1.0 © Aptech Limited

8

Session

Networking

while((strInfo = reader.readLine()) != null) { System.out.println(strInfo);
}} catch (UnknownHostException ex) { ex.printStackTrace();
} catch (IOException ex) { ex.printStackTrace();

println()

Code Snippet 28 shows how to write to a socket.
Code Snippet 28:
Socket socket;
String host = “localhost”; String strInfo = “”;
inal int PORT = 5000; PrintWriter writer = null; try {
// Creates a Socket object socket = new Socket(host, PORT);
// Retrieves the output stream of the socket
writer = new PrintWriter(socket.getOutputStream());
// Writes to a socket writer.println(“Hello World”);
} catch (UnknownHostException ex) {ex.printStackTrace();
} catch (IOException ex) { ex.printStackTrace();
}

8.5 ServerSocket Class
The ServerSocket class uses the SocketImpl to run actual socket operations. This helps the user
change the socket implementation depending on the firewall used by the system. This is done using the
SocketImplFactory method.

8.5.1 ServerSocket

ServerSocket class creates servers that listen for local or remote client programs that connect to them
on a specified published port. ServerSocket class has different constructors that allow the programmer

to specify the port number to connect, the maximum queue length for incoming connections and the IP
address to which the socket binds. An IP address also known as binding address will typically be 127.0.0.1
meaning that the server socket will be listening on the local machine.
A BindException or IOException is thrown when an attempt is made to bind to a port when an already
existing server socket is listening to that port. Only one process or thread can listen to a particular port
at a time.

V 1.0 © Aptech Limited

Concepts

The ServerSocket class is used to represent the server side of the two-way communication. The
ServerSocket has to bind to a specific port which should be free and available. If the port is being used
by any other application, an exception is thrown.

8

Session

Networking

If the ServerSocket class is successful in binding to a port, it then waits and listens for the client request
to establish connections. The ServerSocket class has several constructors to create a server socket.
However, the most commonly used constructor is:

public ServerSocket(int port) throws IOException

This constructor takes a port number as an argument. The specified port should be available to use,
failing which an exception is thrown. The ServerSocket class binds to this specified port, and if
successful, can later listen for client requests.
Syntax:
public ServerSocket(int port) throws IOException

where,
port: is an integer which represents the specified port to bind. It can have a value between

0 to 65535.

Code Snippet 29 shows how to bind server socket to the port number 5000.
Code Snippet 29:
ServerSocket server; final int PORT = 5000; try {
server = new ServerSocket(PORT);
} catch (IOException ex) { System.out.println(“Failed to bind”);
}

8.5.2 Creating ServerSocket Instance
The ServerSocket class has a method accept() for listening to client request. Once a ServerSocket
instance is created, you can invoke the accept() method to listen for client request. The accept()
method is a blocking method that is once invoked it will wait till a client requests for a connection.

Concepts

When a client requests for a connection, the accept() method creates a socket object of class Socket
and returns it. This returned object represents a proxy of a client. To communicate with the client, you
retrieve the InputStream and OutputStream of this proxy socket object.

V 1.0 © Aptech Limited

8

Session

Networking

Code Snippet 30 shows how to use an instance of a ServerSocket class to retrieve a proxy of the client
and its associated input and output streams.
Code Snippet 30:
ServerSocket server;
// Proxy of a client Socket client; inal int PORT = 5000; PrintStream ps = null;
BufferedReader reader = null; try {
// Creates a ServerSocket object server = new ServerSocket(PORT);
// Retrieve a proxy of the client client = server.accept();
// Retrieves the input stream of the client socket
reader = new BufferedReader(new InputStreamReader(client.
getInputStream()));
// Retrieves the output stream of the socket ps = new PrintStream(client.
getOutputStream());
}catch (IOException ex) { System.out.println(“Failed to bind”);
}

8.5.3 Methods of ServerSocket Class
Some of the methods of the ServerSocket class are listed in table 8.9.

Steps

getInetAddress()
close()

isBound()
getLocalPort()

Description
The getInetAddress() method returns the local address
of the server socket to which it is bound. The local address is
returned as an Internet Protocol (IP) address.
The close() method is used to close the server socket.
The is Bound() method is used to retrieve the binding state of
the server socket.
getLocalPort()

Table 8.9: Methods of ServerSocket
getInetAddress()

Code Snippet 31 shows how to retrieve the Internet Protocol address to which the server socket is
bound.
Code Snippet 31:

V 1.0 © Aptech Limited

Concepts

8

Session

Networking

...
InetAddress inetAddress; ServerSocket server; final int PORT = 5000; try {
// Create a ServerSocket object server = new ServerSocket(PORT);
// Retrieve the IP address. inetAddress = server.getInetAddress();
// Retrieve the IP address. inetAddress = server.getInetAddress();
System.out.println(“IP address : “ + inetAddress.getHostAddress());
} catch(IOException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}
...

close()

Code Snippet 32 shows how to close the server socket.
Code Snippet 32:
...
ServerSocket server; inal int PORT = 5000; try {
// Create a ServerSocket object server = new ServerSocket(PORT);
...
ServerSocket server;
inal int PORT = 5000;
try {
// Create a ServerSocket object server = new ServerSocket(PORT);
...
// Close the server socket server.close();
System.out.println(“Server socket closed.”);

Concepts

} catch(IOException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited

8

Session

Networking

isBound()

Code Snippet 33 shows how to check whether the server socket is bound to its IP address.
Code Snippet 33:
ServerSocket server; inal int PORT = 5000; try {
// Create a ServerSocket object server = new ServerSocket(PORT);
...
// Check if the server socket is bound to its IP address if (server.
isBound()) {
System.out.println(“Server socket is bound.”);
}
} catch(IOException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

getLocalPort()

Code Snippet 34 shows how to retrieve the local port on which the server socket is listening.
Code Snippet 34:
...
int listenPort; ServerSocket server; inal int PORT = 5000;
try {
// Create a ServerSocket object server = new ServerSocket(PORT);
// Retrieve the local port on which the server socket is listening.
listenPort = server.getLocalPort();
System.out.println(“Listen Port : ” + listenPort);
} catch(IOException ex) {
System.out.println(“Exception : “ + ex.getMessage());
...

8.6 Datagram
Applications communicate via datagram to send and receive independent packets of information. For
such data transfers it is not required to have a dedicated point to point channel. The delivery of datagram
information or the order in which the data travels is not guaranteed.

V 1.0 © Aptech Limited

Concepts

}

Session

8
Networking

8.6.1 Datagram
A datagram is an independent, self-contained message sent over the network whose arrival, arrival
time, and order of content are not guaranteed. ServerSocket and Socket are used to establish a reliable
communication that is data transmitted from one end will reach the other end.
Datagram packets are used to employ a connectionless packet delivery service. Each message is routed
based solely on information contained within that packet. Multiple packets sent from one machine to
another might be routed differently, and might arrive in any order. Packets delivery by a datagram is not
guaranteed.
Figure 8.6 displays a datagram.

Figure 8.6: Datagram

8.6.2 Creating a Datagram Packet
The java.net package provides the DatagramPacket class to create a datagram packet. The
DatagramPacket has several constructors to create datagram packet. The most commonly used
constructors of DatagramPacket are listed in table 8.10.

Constructors

Description

Concepts

DatagramPacket(byte[], Constructs a datagram packet for receiving data into the buffer
int)
of specified length. The size of data to be received should be less

than or equal to the buffer length.
DatagramPacket(byte[], Creates a datagram packet to be sent to the address specified
int, InetAddress, int) by address on the port specified by port. To transmit this packet,
it uses the buffer specified by variable buf having a capacity
specified by variable length.
Table 8.10: Constructors of DatagramPacket

V 1.0 © Aptech Limited

8

Session

Networking

DatagramPacket(byte[], int

Code Snippet 35 shows how to create a datagram packet with a buffer size of 256 bytes to receive
a packet of data.
Code Snippet 35:
// Creates buffer of size 256 bytes byte[] buf = new byte[256];
// Creates an object of DatagramPacket of size same as buffer
DatagramPacket packet = new DatagramPacket(buf, buf.length);

DatagramPacket(byte[], int, InetAddress, int)

Code Snippet 36 shows how to create a datagram packet to send a packet of data to a host named
Joe1.
Code Snippet 36:
// Creates buffer of size 256 bytes byte[] buf = new byte[256];
inal int PORT = 5000; String host = “Joe1”;
InetAddress address = null;
// Get the IP address of the host try {
address = InetAddress.getByName(host);
} catch (UnknownHostException ex) { ex.printStackTrace();
}// Creates a datagram packet to send to the host
DatagramPacket packet = new DatagramPacket(buf, buf.length, address,
PORT);

8.6.3 Creating Datagram Socket
DatagramSocket class represents a socket for sending and receiving datagram packets. Each packet of

data sent or received on a datagram socket is individually addressed and routed. The most commonly
used constructor of DatagramSocket are listed in table 8.11.
DatagramSocket(int)
DatagramSocket(int,
InetAddress)

Description
Constructs a datagram socket and binds it to the specified port
on the local host machine.
Constructs a datagram socket bound to the local address specified
by the variable. If socket cannot be opened or bound to the port
specified, a SocketException is generated.

Table 8.11: Constructors of DatagramSocket

V 1.0 © Aptech Limited

Concepts

Constructors

8

Session

Networking

DatagramSocket(int)

Code Snippet 37 shows how to create a datagram socket and bind it to the port number 5000.
Code Snippet 37:
inal int PORT = 5000;
DatagramSocket socket = null; try
{
socket = new DatagramSocket(PORT);
}
catch(SocketException ex)
{
System.out.println(“Could not create a datagram socket.”);
}

DatagramSocket(int, InetAddress)

Code Snippet 38 shows how to create a datagram socket listening on port number 5000 on a server
named Yasmin1.
Code Snippet 38:
final int PORT = 5000; DatagramSocket socket = null; InetAddress address =
null; try {
address = InetAddress.getByName(“Yasmin1”);
// Create the datagram socket
socket = new DatagramSocket(PORT,address);
}
catch(UnknownHostException ex) { ex.printStackTrace();
} catch(SocketException ex) {
System.out.println(“Could not create a datagram socket.”);

Concepts

}

8.6.4 Use of Datagram Socket
Once a DatagramSocket instance is created, it can be used to send and receive data using packets. The
DatagramSocket methods to send and receive packets are listed in table 8.12.

V 1.0 © Aptech Limited

8

Session

Networking

Constructor

Description

public void
The send() method is used to send a datagram packet using a
send(DatagramPacket p) DatagramSocket instance.
public void
The receive() method is used to receive a datagram packet
receive(DatagramPacket using a DatagramSocket instance. The datagram packet
p)
received comprises the data, the sender’s IP address and the port

number.

Table 8.12: Methods of DategramSocket

public void send(DatagramPacket p)

Code Snippet 39 shows how to send a datagram packet using a datagram socket.
Code Snippet 39:
String host = “Joe1”; byte[] buf = new byte[256]; try
{
//Retrieve the IP address of the host InetAddress address = InetAddress.
getByName(host);
//Create a datagram packet
DatagramPacket packet = new DatagramPacket(buf, buf.length, address,
4445);
// Create a datagram socket to send the packet DatagramSocket socket = new
DatagramSocket();
// Send the packet socket.send(packet);
} catch (SocketException ex)
{ex.printStackTrace();
}
catch (UnknownHostException ex)
{ex.printStackTrace();
}
{ex.printStackTrace();
}

public void receive(DatagramPacket p)

Code Snippet 40 shows how to receive a datagram packet using a datagram socket.

V 1.0 © Aptech Limited

Concepts

catch (IOException ex)

Session

8
Networking

Code Snippet 40:
// Create a buffer to store data byte[] buf = new byte[256];
// Create a datagram socket to receive the packet DatagramSocket socket =
new DatagramSocket();
// Create a datagram packet to store data sent by host DatagramPacket
packet = new DatagramPacket(buf, buf.length);
// Receive the packet socket.receive(packet);

8.6.5 Methods of DatagramPacket Class
The important methods of the DatagramPacket class are listed in table 8.13.

Constructor

Description

public InetAddress
getAddress()

public int getPort()
public byte[]
getData()
public void
setData(byte[] data)
public void
setPort(int port)

The method returns the IP address of the machine to which the
datagram packet is being sent or received.
The method returns the port number of the remote host to which
the datagram packet is being sent or received.
The method returns the data buffer. The data received or the
data to be sent starts from the offset in the buffer, and continues
till the specified length. By default the offset is zero.
The method sets the data buffer for the packet. The offset is set
to zero, and the length of data is set to the length of the data
array.
The method sets the port number on the remote host to which
this datagram packet is being sent.

Table 8.13: Methods of DatagramPacket Class

public InetAddress getAddress()

Code Snippet 41 shows how to retrieve the IP address from the datagram packet.
Code Snippet 41:

Concepts

// Creates buffer of size 256 bytes byte[] buf = new byte[256];
// Creates a DatagramPacket object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
// Retrieves the IP address from the datagram packet InetAddress address =
packet.getAddress();

V 1.0 © Aptech Limited

8

Session

Networking

public InetAddress getAddress()

Code Snippet 42 shows how to retrieve the data from the packet.
Code Snippet 42:
// Creates buffer of size 256 bytes byte[] buf = new byte[256];
DatagramPacket packet = null;
try{
// Creates a DatagramSocket object
DatagramSocket socket = new DatagramSocket(); packet = new
DatagramPacket(buf, buf.length);
// Receive the packet through the socket socket.receive(packet); catch
(SocketException ex){ex.printStackTrace();
}} catch (IOException ex)
{ex.printStackTrace();
}// Retrieves the data from the packet buf = packet.getData();

public byte[] getData()

Code Snippet 43 depicts how to assign data to the data packet.
Code Snippet 43:
// Creates buffer of size 256 bytes byte[] buf = new byte[256];
String strData = “the data to be sent”;
// Creates a DatagramPacket object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
// Sets the data to the packet packet.setData(strData.getBytes());

public void setPort(int port)

Code Snippet 44 shows how to set the port of the remote host.
final int PORT = 5000;
// Creates buffer of size 256 bytes byte[] buf = new byte[256];
// Creates a DatagramPacket object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
// Sets the port packet.setPort(PORT);

V 1.0 © Aptech Limited

Concepts

Code Snippet 44:

Session

8
Networking

8.6.6 Broadcasting to Multiple Recipients
A MulticastSocket is a java.net utility that is used on the client-side to listen for messages that the
server broadcasts to multiple clients. A client may or may not send any message to the server. Here is an
example code snippet to send messages from a server to multiple clients.
Code Snippet 45 shows server code.
Code Snippet 45:
import java.io.*;
public class MulticastServer {
public static void main(String[] args) throws IOException {
new MulticastServerThread().start();
}}

The server is identified with a new name and creates a MulticastServerThread which contains the
heart of the server. The only method explicitly implemented in MulticastServerThread is the run
method.
Code Snippet 46 shows the implementation of MulticastServerThread in the run() method.
Code Snippet 46:
public void run() {
while (moreQuotes) {
try {byte[] buf = new byte[256];
// don’t wait for request...just send a quote
String dString = null;
if (in == null)dString = new Date().toString();
else dString = getNextQuote();
buf = dString.getBytes();

Concepts

InetAddress group = InetAddress.getByName(“204.0.115.0”);

V 1.0 © Aptech Limited

8

Session

Networking

DatagramPacket packet;
packet = new DatagramPacket(buf, buf.length, group, 4346);
socket.send(packet);
try { sleep((long)Math.random() * FIVE_SECONDS);
} catch (InterruptedException e) { }
}

catch (IOException e) {
e.printStackTrace();
moreQuotes = false;

} }

Since the server needs to address multiple clients, the InetAddress (204.0.115.0) and the port
number(4346) are hard-coded. The DatagramPacket is destined for all clients listening to port number
4346 who are member of the “204.0.115.0” group.
To listen to port number 4346, the new client program should create its MulticastSocket with the
port number. To become a member of the “204.0.115.0” group, the client calls the MulticastSocket’s
joinGroup method with the InetAddress that identifies the group. Now, the client is set up to receive
Datagram packets destined for the port and group specified.
Code Snippet 47 shows how the client program receives Datagram packets.
Code Snippet 47:
MulticastSocket socket = new MulticastSocket(4346);
InetAddress group = InetAddress.getByName(“204.0.115.0”);
socket.joinGroup(group);
DatagramPacket packet;
for (int i = 0; i < 10; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println(“Quote of the Moment: “ + received);
}socket.leaveGroup(group);
socket.close();

V 1.0 © Aptech Limited

Concepts

String received = new String(packet.getData());

Session

8
Networking

8.6.7 Multicast Socket
Sending and receiving IP multicast packets is done using the multicast datagram socket class.
MulticastSocket has some additional capabilities that let it form groups of other multicast hosts on the
Internet.
A multicast group is specified by a class D IP address and by a standard UDP port number. Class D IP
addresses are in the range 224.0.0.0 to 239.255.255.255. The address 224.0.0.0 is reserved and should
not be used.
To join a multicast group, it is required to create a MulticastSockets with the desired port number
and invoking the joinGroup() method. This is demonstrated in Code Snippet 48.
Code Snippet 48:
// join a Multicast group and send the group salutations
String msg = “Hello”;
InetAddress group = InetAddress.getByName(“228.5.6.7”);
MulticastSocket s = new MulticastSocket(6789);
s.joinGroup(group);
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), group,
6789);
s.send(hi);
// get their responses!
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.receive(recv);
...
// leave the group...
s.leaveGroup(group);
MulticastSockets are created using one of the constructors listed in table 8.14.

Concepts

Constructor

MulticastSocket()

Description
Creates a Multicast Socket

MulticastSocket(int
Creates a Multicast socket and bind it to a port number.
port)
MulticastSocket(Socket Creates a Multicast Socket bound to a specified socket address.
Address bindaddr

Table 8.14: Constructors of MulticastSockets
V 1.0 © Aptech Limited

8

Session

Networking

MulticastSocket()

Code Snippet 49 shows how to create a Multicast Socket bound to a specified socket address.
Code Snippet 49:
public More ...MulticastSocket(int port) throws IOException {
this(new InetSocketAddress(port));
}

All recipients subscribing to a given host and port number receive a multicast group message. It is
not necessary for the socket to be a member of the same group to send messages to it. When a
socket subscribes to a group/host, it gets diagrams sent by other hosts to the group, same as the
other members. Using the leaveGroup(InetAddress) method s socket can forgo membership
to a group. It is possible for multiple MulticastSockets to be part of a group and subscribe to
the port to receive group datagrams.
MulticastSockets are used by using the methods listed in table 8.15.

Method

getInterface()

Description
Retrieves the network address used for multicast packets.

getLoopbackMode()

Table 8.15: Methods of MulticastSockets

getInterface()

Code Snippet 50 shows how to retrieve the network address used for multicast packets.
Code Snippet 50:

V 1.0 © Aptech Limited

Concepts

Gets the setting for local loopback of multicast datagrams.
getNetworkInterface() Gets the multicast network interface set.
getTimeTsoLive()
Retrieves the default time- to- live for multicast packets sent out
on a socket.
joingGroup()
Joins the multicast group.
leaveGroup
Leaves the multicast group.
Send(Datagram Packet, Sends a datagram packet to the destination, with a specified TTL
byte)
(time- to-live) for the socket.
setInterface(InetAddr Sets the multicast network interface used by methods whose
ess)
behavior would be affected by the value of the network
interface.
setNetworkInterface(Ne Specifies the network interface for outgoing multicast datagram
tworkInterface netIf) sent on this socket.
setTimeToLive()
Set the default time-to-live for multicast packets sent out on this
MulticastSocket in order to control the scope of the multicasts.

8

Session

Networking



public void More ...setInterface(InetAddress inf) throws
SocketException {
if (isClosed()) {

throw new SocketException(“Socket is closed”);

}

synchronized (infLock) {
getImpl().setOption(SocketOptions.IP_MULTICAST_IF, inf);
infAddress = inf;

}
}

setNetworkInterface(NetworkInterface netIf)

Code Snippet 51 shows how to specify the network interface for outgoing multicast datagram on
a socket.
Code Snippet 51:

public void More ...setNetworkInterface(NetworkInterface netIf)
throws SocketException {
synchronized (infLock) {
getImpl().setOption(SocketOptions.IP_MULTICAST_IF2, netIf);
infAddress = null;
}
}

getLoopbackMode()

Concepts

Code Snippet 52 show how to get the setting for local loopback of datagrams.
Code Snippet 52:
public boolean More ...getLoopbackMode() throws SocketException {
return ((Boolean)getImpl().getOption(SocketOptions.IP_MULTICAST_
LOOP)).booleanValue();
}

V 1.0 © Aptech Limited

8

Session

Networking

setTimeToLive()

Code Snippet 53 shows how to send datagram packets to a destination, with a TTL set other than
the default one for the socket.
Code Snippet 53:
public void More ...send(DatagramPacket p, byte ttl)
{

if (isClosed())
throw new SocketException(“Socket is closed”);
synchronized(ttlLock) { synchronized(p) {
if (connectState == ST_NOT_CONNECTED) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
if (p.getAddress().isMulticastAddress()) {
security.checkMulticast(p.getAddress(), ttl);
} else {

security.checkConnect(p.getAddress().getHostAddress(),
p.getPort());
} } } else {
InetAddress packetAddress = null;
packetAddress = p.getAddress();
if (packetAddress == null) {
p.setAddress(connectedAddress); p.setPort(connectedPort);
} else if ((!packetAddress.equals(connectedAddress)) ||
p.getPort() != connectedPort) {
throw new SecurityException(“connected address and packet
address” + “ differ”);
}

} byte dttl = getTTL();

} getImpl().send(p);
}

V 1.0 © Aptech Limited

Concepts

try { if (ttl != dttl) {

Session

8
Networking

8.7 Network Interface
The point of interconnection between a computer and a private or public network is termed as a network
interface. It can be either a hardware device such as a Network Interface Card (NIC) or a software
implementation such as IPv6. The java.net.NetworkInterface class represents both types of
interfaces.

8.7.1 Use a Socket with a Network Interface
The point of interconnection between s computer and a network is the network interface. It is contained
in a network interface card or NIC, bit does not need a physical form. It can also be implemented in
software. To send or receive data from server, network interfaces need sockets. These sockets are created
using the soc.connect() method.
The point of interconnection between s computer and a network is the network interface. It is contained
in a network interface card or NIC, bit does not need a physical form. It can also be implemented in
software. To send or receive data from server, network interfaces need sockets. These sockets are created
using the soc.connect() method.
Code Snippet 54 shows us how to create a socket to send data to a server.
Code Snippet 54:
Socket soc = new java.net.Socket();
soc.connect(new InetSocketAddress(address, port));

The system decides which system is used to send the data. When a socket is created and bound to an
address, the system uses the associated interface. The user can also query the system for the appropriate
interface and find the addresses on the interface to be used.
Code Snippet 55 shows how to create a socket bound to an address and sends data through the
network.
Code Snippet 55:
NetworkInterface nif = NetworkInterface.getByName(“bge0”);
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
Socket soc = new java.net.Socket();

Concepts

soc.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
soc.connect(new InetSocketAddress(address, port));

The NetworkInterface can also be used to identify the local interface on which a multicast group is
to be created.

V 1.0 © Aptech Limited

8

Session

Networking

This is shown on Code Snippet 56.
Code Snippet 56:
NetworkInterface nif = NetworkInterface.getByName(“bge0”);
MulticastSocket ms = new MulticastSocket();
ms.joinGroup(new InetSocketAddress(hostname, port), nif);

8.7.2 NetworkInterface Class
The NetworkInterface class has no public constructor; therefore, you cannot create a new instance of
this class with the new operator. The static methods such as getByInetAddress(), getByName(),
and getNetworkInterfaces() can extract the interface details from the system.
Code Snippet 57 lists all the network interfaces and their addresses on a machine.
Code Snippet 57:
import java.io.*;import java.net.*;
import java.util.*;import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.
getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInfo
rmation(netint);
} static void displayInterfaceInformation(NetworkInterface netint) throws
SocketException {
out.printf(“Display name: %s\n”, netint.getDisplayName());
out.printf(“Name: %s\n”, netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
} out.printf(“\n”); }}

8.7.3 InterfaceAddress Class
This class represents a Network Interface address. When the address is IP4, it an IP address, a subnet
mask and a broadcast address. On the other hand it is an IP address and a network prefix length in the
case of IPv6 address.

V 1.0 © Aptech Limited

Concepts

out.printf(“InetAddress: %s\n”, inetAddress);

Session

8
Networking

Code Snippet 58 is a sample using Network Interface address.
Code Snippet 58:
import java.net.InterfaceAddress;
import java.net.NetworkInterface; import java.net.SocketException;
import java.util.Enumeration; import java.util.List;
public class InterfaceAddressTest {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> en = NetworkInterface.
getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = en.nextElement();
List<InterfaceAddress> inAdd = ni.getInterfaceAddresses();
for (InterfaceAddress ia : inAdd) {
//returns Inet Address System.out.println(ia.getAddress());
//returns Inet Address for the broadcast address
System.out.println(ia.getBroadcast());
//returns network prefix length
System.out.println(ia.getNetworkPrefixLength());
}

} }

}

8.8 What is a Cookie
Java Web applications can use cookies to store information on the client machine. It is usually stored in a
browser’s cache. A cookie which holds data for a single Web session, that is, until you close the browser
is termed as a short term cookie, and a cookie which holds data for a week or a year is termed as a long

Concepts

term cookie.
The CookieManager class is the main entry point for cookie management. An instance of the
CookieManager class is created and a CookiePolicy is set. An URLConnection is opened to the
website of interest. Next, cookies are retrieved from the underlying CookieStore by using the getCookies
method.

V 1.0 © Aptech Limited

8

Session

Networking

8.8.1 HTTP Cookie Management
Code Snippet 59 shows how to retrieve cookies from a Web page.
Code Snippet 59:
import java.net.InterfaceAddress;
import java.net.NetworkInterface; import java.net.SocketException;
import java.util.Enumeration; import java.util.List;
public class InterfaceAddressTest {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> en = NetworkInterface.
getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = en.nextElement();
List<InterfaceAddress> inAdd = ni.getInterfaceAddresses();
for (InterfaceAddress ia : inAdd) {
//returns Inet Address System.out.println(ia.getAddress());
//returns Inet Address for the broadcast address
System.out.println(ia.getBroadcast());
//returns network prefix length
System.out.println(ia.getNetworkPrefixLength());
}

} }

}

8.8.2 HTTP State Management
The HTTP state management mechanism specifies a way to create a stateful session with HTTP requests
and responses. A session is created for exchange of information. Cookies are used to create and maintain
the state information of the session.
Code Snippet 60:
java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);

The default CookieManager constructor is called to create an instance. This is followed by calling the
static setDefault method of CookieHandler class to set the system wide handler. A CookieHandler

V 1.0 © Aptech Limited

Concepts

Code Snippet 60 shows how to create and set a system-wide CookieManager.

Session

8
Networking

object has a call back mechanism to connect a HTTP state policy implementation to the HTTP protocol
handler.
CookieManager uses the default policy CookiePolicy.ACCEPT_ORIGINAL_SERVER. This only
accepts the cookie. So the domain attribute of the Set Cookie method must be set and it must match
the host domain.

Concepts

The CookieManager also forces path match rule when getting the cookies from the cookie store. It
provides the framework for handling cookies and a default implementation for CookieStore.

V 1.0 © Aptech Limited

8

Session

Networking

8.9 Check Your Progress
1. State whether the following statements about networking are true.
A.
B.
C.
D.
E.

TCP is a connection-based protocol that provides a reliable transfer of data between
two computers.
You do not write programs at the lower level like application, instead you generally
program at the transport level.
Java provides the java.net package which contains all the necessary classes to perform
system-independent network communications.
TCP guarantees that data sent from one end of the connection is received at the other
end.
The top most layer in the TCP protocol is the network layer.

(A) A, B, and C
(B) C, D, and E

State whether the statements about port are true.
A.

The destination address identifies the computer.

B.

The port numbers ranging from 0 to 1023 are reserved.

C.
D.
E.

A computer generally has a single physical connection available for the network.
The physical connection is logically numbered within a range of 0 to 65500.
Data transmitted over the Internet is accompanied with the destination address.

(A) A, B, D, and E
(B) B, C, D, and E
3.

(C)
(D)

A, B, and C
A, C, and D

Which of the following statements about URL are true?
A.

The resource can be an HTML page, an image or simply any file.

B.

URL is an acronym for Uniform Resource Location.

C.
D.
E.

The format of the resource name depends on the protocol being used.
In resource name, port number to which you connect has to be specified.
URL is a reference or an address to a resource on the Internet.

(A) A, C, and E
(B) B, D, and E

A, B, and D
A, C, and D

(C)
(D)

A, C, and D
C, D, and E

V 1.0 © Aptech Limited

Concepts

2.

(C)
(D)

Session
4.

8
Networking

Can you match the methods of InetAddress and URL classes against their description?
Feature

Description

(A) getFile()

(1)

Retrieves the IP Address of local host

(B) openStream()

(2)

Retrieves the raw IP Address in textual format

(C) getHost()
(D) getLocalHost()
(E) getHostAddress()

(3)
(4)
(5)

Opens a connection to the URL
Retrieves the host name of the URL
Retrieves the file name of the URL.

(A) A-5, B-3, C-4, D-1, E-2
(B) A-4, B-3, C-5, D-1, E-2
5.

(C)
(D)

A-5, B-3, C-1, D-2, E-4
A-2, B-3, C-1, D-4, E-5

State whether the statements about URLConnection class and openConnection() method are
true.
A.

URLConnection is an abstract class.

B.

A valid URL instance is required to create an instance of URLConnection from the
URL.
If the openConnection() method of the URL class is executed successfully, a
reference to the IOException object is returned.

C.
D.
E.

If the openConnection() method fails to execute, an URLConnection object is
returned.
Instances of URLConnection class can be used to read from and to write to the resource
referenced by the URL.
(C)
(D)

A, B, and D
D and E

Concepts

(A) A, B and E
(B) C and D

V 1.0 © Aptech Limited

8

Session

Networking

8.9.1 Answers
D

2.

C

3.

A

4.

A

5.

A

Concepts

1.

V 1.0 © Aptech Limited

Session

8
Networking

Summary
Transmission Control Protocol (TCP) is a connection-based protocol that provides a reliable low of
data between two computers.

On the Internet, computers communicate with each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP).

URL is an acronym for Uniform Resource Locator. It is a reference or an address to a resource on
the Internet.

The URLConnection is an abstract class that represents the communication link between an
application and a URL.

A socket is one end-point of a two-way communication link between two programs running on
the network.

The ServerSocket class is used to represent the server side of the two-way communication. The
ServerSocket class has to bind to a specific port which should be free and available.

A datagram is an independent, self-contained message sent over the network whose arrival,
arrival time and order of content are not guaranteed.

Concepts

V 1.0 © Aptech Limited

Session 9
Remote Method
Invocation
Welcome to the Session, Remote Method Invocation.
This session gives a brief introduction to distributed computing. It introduces
Java’s Remote Method Invocation, and explains the architecture used
by RMI. The session covers all the necessary steps to write a distributed
application in Java using RMI. Finally the session explains how to execute
RMI applications.
In this Session, you will learn to:

Introduction to RMI

Explain RMI rrchitecture

Explain the steps to implementing RMI

9

Session

Remote Method Invocation

9.1 Distributed Computing
A Java application can run inside a Java Virtual Machine (JVM) and can only invoke the methods of the
classes available inside this JVM. Beyond the realms of this JVM, the application cannot invoke methods
of classes running inside another JVM.
Distributed computing or processing revolves around client-server technology where several client
programs communicate with one or more server applications.
Remote Method Invocation (RMI) allows a Java program running inside a JVM to execute a method of
a class available in another JVM. Remote Method Invocation allows Java applications to support the
distributed computing architecture through the use of client-server technology.
Figure 9.1 displays the distributed computing.

Figure 9.1: Distributed Computing

Java provides the java.rmi package which contains all the necessary classes and interfaces to support
distributed computing in Java. Since Java is platform independent, distributed computing applications
developed using RMI are also platform independent. That means the client and server applications can
be executed on diverse machines and yet be made to communicate amongst themselves.

9.1.2 Need for RMI
Although Java provides you with Socket Programming, it is a low level technology which only transmits
bytes and not objects. RMI allows to serialize and transmit objects.

V 1.0 © Aptech Limited

Concepts

9.1.1 RMI

Session

9
Remote Method Invocation

Java is a platform-independent language. Client and Server applications can run on diverse operating
systems which can have different byte order, also called endian. Windows is a little endian system, that
is, lower order bits are placed before the higher order bits in the machine architecture. Unix is a higher
endian system where, higher order bits are placed before lower order bits.
RMI, unlike Socket Programming, takes into account the endian during method invocations.

9.2 RMI Architecture
The Remote Method Invocation (RMI) is based on a three layered architecture. These three layers are just
below the application layer on the server and client side.
The three layers of the RMI architecture are:

Stub and Skeleton Layer

The Stub resides on the client side, and the Skeleton on the server side.
This layer performs:
1.

Marshalling and Unmarshalling data.

2.

Transmitting and receiving data to and from the Remote Reference Layer.

Marshalling is the process of converting data into an on-the-wire format before putting them on
the wire (network). RMI uses serialization to perform marshalling. Unmarshalling is the reverse of
this process.

Remote Reference Layer

Concepts

This layer is responsible for the invocation of the remote method. If the marshalling process
succeeds, the client-side remote reference layer receives the remote reference and marshalled
arguments from the stub. This layer converts the client request into a low-level RMI transport
request and forwards it to transport layer.

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

Transport Protocol Layer
This layer is responsible for setting up connections using sockets. It listens for incoming calls,
and manages requests from remote reference layer. The transport layer of stub and skeleton
communicates with the low-level RMI transport protocol.

Figure 9.2 displays the RMI Architecture.

Figure 9.2: RMI Architecture
Note - Data is converted into a serialized form in an on-the-wire format before transporting it over

network so that it can be transmitted over the wire through a socket. Serialization allows converting
objects into a stream of bytes. Classes of objects which are used as arguments and return types in
remote methods should implement the interface Serializable.

9.2.1 RMI Architecture Layer
The components of a RMI application are:

Remote Interface
An RMI application has to expose methods, which remote clients can invoke. These methods which
are meant to be remote, should be defined in an interface which extends the java.rmi.Remote
interface. The java.rmi.Remote is a marker interface and simply serves to distinguish interfaces
which are non-remote.
Implementation Class
The remote interface has to be implemented by a class to provide the implementation (methodbodies) of the remote methods. The Implementation class implements the remote interface and
provides the implementation of the remote methods. This implementation class should extend
from the java.rmi.server.UnicastRemoteObject. Generally, the Server application class
extends UnicastRemoteObject.

V 1.0 © Aptech Limited

Concepts

9

Session

Remote Method Invocation

Stub
The Stub class constitutes one part of Stub and Skeleton Layer. This stub resides on the client
side; if it is not available the JVM will download it to the client side.

Skeleton
The Skeleton class constitutes one part of Stub and Skeleton Layer. The Skeleton resides on
the server side.

9.3 Implementing RMI
The process to create RMI program is to create Server code and remote interface. .

9.3.1 Creating Remote Interface
To create a remote interface, you should first identify all the methods which are meant to be remotely
invoked by remote clients.

Define an interface which extends java.rmi.Remote
The remote interface can have any name of your choice, but it should extend the java.rmi.
Remote interface. This marker interface indicates that your interface is indeed a remote interface.
Syntax:
public interface Interface-Name extends java.rmi.Remote { }

Code Snippet 1 shows how to define an interface HelloInterface.
Code Snippet 1:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloInterface extends Remote {
}

Concepts

Declare the remote methods signatures
All the methods which are meant to be remotely invoked are declared in the remote interface. Remote clients can only invoke these methods. Methods from other interfaces which are non-remote
are not available for clients to invoke.
Syntax:
public interface Interface-Name extends java.rmi.Remote {
public Return-type methodName(Parameters if any)
}

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

Code Snippet 2 shows how to declare the remote method signature.
Code Snippet 2:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloInterface extends Remote {
// Declare all the remote method signatures
public String sayHello(String name);}

All these methods should be qualified to throw java.rmi.RemoteException
All the remote methods declared should be qualified to throw java.rmi.RemoteException.
This is required to identify catastrophic events, such as network failure, server not ready, and so on,
and propagate these events to remote clients.
Syntax:
public interface Interface-Name extends java.rmi.Remote {
public Return-type methodName(Parameters if any) throws
RemoteException
}

Concepts

Code Snippet 3 shows how to qualify the remote method to throw a RemoteException.

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

Code Snippet 3:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloInterface extends Remote
{
// Qualifies method to throw RemoteException
public String sayHello(String name) throws RemoteException;
}

9.3.2 Creating Remote Class
The remote class is the implementation class which provides the implementations of remote methods.
To create a remote class perform the following steps:

Define a class which extends java.rmi.server.UnicastRemoteObject
The remote implementation class should extend from the UnicastRemoteObject. This super
class is required to export the remote object using the RMI transport mechanism. Also this class is
responsible to download the stub which communicates with the remote object.
Syntax:
public class ImplementationClassName extends UnicastRemoteObject

where,
ImplementationClassName: is any valid class name of your choice.

Code Snippet 4 shows how to define a remote class.
Code Snippet 4:
public class HelloServerImpl extends UnicastRemoteObject { }

Concepts

Implement the remote interface(s)
The remote implementation class should implement all the remote interfaces. This class is free to
implement any other non-remote interfaces, but their methods are not available remotely for client invocations. Only the methods declared in the remote interfaces are exposed to the client for
remote invocations.
Syntax:
public class ImplementationClassName extends UnicastRemoteObject implements RemoteInterface

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

where,
RemoteInterface: is an interface which extends the java.rmi.Remote interface. At least

one remote interface is required.

Code Snippet 5 shows how to implement the remote interface HelloInterface.
Code Snippet 5:
public class HelloServerImpl extends UnicastRemoteObject implements
HelloInterface
{}

Provide a constructor which throws RemoteException
The implementation class which extends the UnicastRemoteObject should have a constructor
which throws a RemoteException. This is required because the super class constructor attempts
to create and export a new remote object using an anonymous port.
Syntax:
public ImplementationClassName() throws RemoteException { }

Code Snippet 6 shows how to provide a constructor which throws exception.
Code Snippet 6:
public class HelloServerImpl extends UnicastRemoteObject implements
HelloInterface {
public HelloServerImpl() throws RemoteException {
super(); } }

Provide the implementation of all remote methods
The implementation class implements the remote interfaces, and should provide the method implementation of all method signatures from the remote interfaces.
Syntax:
public Return-type methodName(Parameters if any) throws RemoteException
{ }

Concepts

Code Snippet 7 shows the implementation of the remote method from the HelloInterface.

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

Code Snippet 7:
public class HelloServerImpl extends UnicastRemoteObject implements
HelloInterface {
public HelloServerImpl() throws RemoteException {
super(); }
public String sayHello(String name) throws RemoteException {
return “Hello “ + name;
}}

9.3.3 Remote Server
The Remote Server is any class which has a main() method to execute as an application. To make the
remote methods available for clients for remote invocations, the server class has to perform a few setup
procedures. After completion of these setup steps, the server is read to allow clients to make remote
invocations.

9.3.4 Instance of Implementation Class
The first step to set up the Remote Server is creating an instance of the Implementation class. The server
class creates an instance of the implementation class so that the remote methods are available on the
server side. These remote methods are not yet ready to be invoked remotely by clients. The super class
constructor exports the remote object and makes it available for receiving incoming calls.
Code Snippet 8 shows how to create an instance of the implementation class.
Code Snippet 8:
// Create an instance if the implementation class
HelloServerImpl remoteObject = new HelloServerImpl();

Concepts

9.3.5 Creating Java RMI Registry
The second step to set up the Remote Server is creating a JAVA RMI Registry programmatically. An
RMI Registry is a naming service which runs on the server side. This service can be started manually
using the rmiregistry.exe application or created programmatically. The RMI Registry allows clients
to get a reference (stub) to a remote object. The createRegistry() method of the java.rmi.
registry.LocalRegistry class is used to create registry programmatically. The static method
LocateRegistry.getRegistry() that takes no arguments returns a stub that implements the
remote interface java.rmi.registry. The bind() method of the Registry class is used to bind the
remote object reference with a name in the registry. The syntax of various methods is as follows:
Syntax:
public static Registry createRegistry(int port) throws RemoteException

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

where,
port: is integer which specifies the port number to bind.
Registry: return type is a Registry instance which is exported on the local host that accepts re-

quests on the specified port.
Syntax:

public static Registry getRegistry() throws RemoteException

where,
Registry: is a reference to the remote object Registry for the local host on the default registry

port of 1099.
Syntax:

public static Registry getRegistry(int port) throws RemoteException

where,
Registry: is a reference to the remote object Registry for the local host on the specified port.
Syntax:
void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException,
AccessException

where,
name: is a String which specifies a name to bind for the remote object reference.
obj: is the reference to the remote object.

Code Snippet 9 shows how to create the RMI registry programmatically.
Code Snippet 9:
// Listen on default RMIRegistry port 1099
Registry registry = LocateRegistry.createRegistry(1099);

The following snippet shows how to retrieve a stub, the remote object reference that implements the
remote interface, java.rmi.registry.Registry.
registry.bind(“Hello”, stub);

V 1.0 © Aptech Limited

Concepts

Registry registry = LocateRegistry.getRegistry();

Session

9
Remote Method Invocation

9.3.6 Binding the Remote Object
The third step to set up the Remote Server is binding the Remote object with a name in the RMI Registry.
The server application has to bind the remote object with a name in the registry.
The clients have to lookup for this name to retrieve the stub which is the remote object reference. The
java.rmi.Naming class has a method rebind() to bind the name to the registry.
The rebind() method works similar to the bind() method except that it allows binding a name to an
existing name. The bind() method in such a case would throw AlreadyBoundException exception.
Syntax:
void rebind(String name, Remote obj) throws RemoteException, AccessException

where,
name: is a String which specifies a name to bind for the remote object reference
obj: is the reference to the remote object.

Code Snippet 10 shows how to specify a name in a URL, and bind the remote object in the rmi registry.
Code Snippet 10:
String name = “rmi://localhost:1099/HelloServer”;
// Creates an instance if the implementation class
HelloServerImpl remoteObject = new HelloServerImpl();
// Binds the remote object with a name in the registry
Naming.rebind(name, remoteObject);

9.3.7 Creating Client
A RMI Client is any application which needs to invoke the remote methods of a RMI Server. To be able to
invoke the methods remotely, the RMI client has to perform the following steps:

Lookup in the RMIRegistry for the name

Concepts

The RMI client requires the stub which is the remote object reference to invoke the methods remotely. This remote object is bound to the rmi registry by the rmi server. The RMI client uses the
lookup() method of java.rmi.Naming class to look for the name bound in the registry.
Syntax:
RemoteInterface
name);

remoteObject

=

(RemoteInterface)

V 1.0 © Aptech Limited

Naming.lookup(String

9

Session

Remote Method Invocation

where,
remoteObject: is the object of the RemoteInterface.
name: is a String in a URL format which specifies the name to look up.

Code Snippet 11 shows how to look up for the name bound in the registry.
Code Snippet 11:
// Lookup for the name HelloServer in the rmi registry
HelloInterface objReference = (HelloInterface)
Naming.lookup(“rmi://localhost:1099/HelloServer”);

Use the Remote object reference to invoke methods
If the lookup succeeds, the client acquires a stub. The lookup() method returns a java.rmi.
Remote object; hence, it is required to cast it with the appropriate remote interface. The remote
object reference can now be used to invoke the remote methods.
Syntax:
Return-type variable = remoteObject.methodName(parameters);

where,
variable: is either a primitive or an object depending on the return type of the method.
parameters: are any valid parameters declared in the method definition.

Code Snippet 12 shows how to invoke the remote method sayHello(), with the remote object
reference.
Code Snippet 12:
// Invoke the remote method, and assign the result to a string
//strResult
String strResult = objReference.sayHello(“Tom”);
// Display the result

9.3.8 Executing RMI Applications
An RMI application can be executed in two different ways.

Starting the RMI Registry manually
In this method, the RMIRegistry has to be executed manually. Start a DOS prompt and execute the
rmiregistry.exe application. This application is available in the bin directory of your installed

V 1.0 © Aptech Limited

Concepts

System.out.println(strResult);

Session

9
Remote Method Invocation

Java’s home directory. Next, execute the RMI server application in the second DOS prompt. Finally,
execute the RMI client in the third DOS prompt.

Creating the RMI Registry programmatically
In this method, the RMI server starts the RMI Registry programmatically. Execute the RMI server
application in one DOS prompt. In another DOS prompt execute the RMI client application.

9.4 list(String name) Method
The list() method is used to retrieve all the names bound to a rmi-registry. The names are in URL
format. The URL format has the form //host:port/name. Only the names available in the registry at
the point of invocation of this method are returned.
Syntax:
public static String[] list(String name) throws RemoteException,
MalformedURLException

where,
name: is a String representing the name in URL format bound in the registry.
String[]: is a String array representing the names in URL format bound in the registry.

Code Snippet 13 shows how to retrieve all the names bound in the rmi registry.
Code Snippet 13:
String[] boundedNames;
String name = “rmi://localhost:1099/HelloServer”;
try {
// Create an instance of the implementation class
HelloServerImpl remoteObject = new HelloServerImpl();
// Rebind the remote object with a new name in the registry
Naming.rebind(name, remoteObject);
...

Concepts

...
}

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

// Retrieve all the names bound in the registry
boundedNames = Naming.list(name);
// Display all the names bound in the registry
for (int i = 0; i< boundedNames.length; ++i) {
System.out.println(boundedNames[i])
}
} catch (RemoteException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (MalformedURLException ex) {
System.out.println(“Exception : “ + ex.getMessage());

9.4.1 unbind(String name) Method
The unbind() method destroys the binding for the specified name which is associated with the remote
object in the registry.
Syntax:
public static void unbind(String name) throws RemoteException, NotBoundException,
MalformedURLException

where,
name: is a String representing the name in URL format bound in the registry.

Code Snippet 14 shows how to unbind the name associated with a remote object.
Code Snippet 14:
String name = “rmi://localhost:1099/HelloServer”;
try {
// Create an instance of the implementation class
HelloServerImpl remoteObject = new HelloServerImpl();
// Bind the remote object with a name in the registry
...
...
// Unbind the name bound in the registry

V 1.0 © Aptech Limited

Concepts

Naming.rebind(name, remoteObject);

Session

9
Remote Method Invocation

Naming.unbind(name);
System.out.println(name + “ has been successfully unbound”);
} catch (RemoteException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (NotBoundException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (MalformedURLException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

9.5 getRegistry(String name) Method
The getRegistry() method is used to retrieve a reference of the remote object registry on the specified
host name, and the default registry port 1099.
Syntax:
public static Registry getRegistry(String host) throws RemoteException

where,
host: is a String representing the host name where the registry is running.
Registry: is a reference to the remote object registry for the specified host on port number

1099.

Code Snippet 15 shows how to retrieve a reference of the remote object registry.
Code Snippet 15:
Registry registry;
String name = “rmi://localhost:1099”;
try {
// Create an instance of the implementation class

Concepts

HelloServerImpl remoteObject = new HelloServerImpl();
// Retrieve the registry

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

registry = LocateRegistry.getRegistry(name);
// Bind the remote object with a name in the registry
registry.rebind(“HelloServer”, remoteObject);
System.out.println(“Remote object bound successfully”);
} catch (RemoteException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (MalformedURLException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

9.5.1 getRegistry(String name, int port) Method
The getRegistry() method is used to retrieve a reference of the remote object registry on the specified
host name, and the specified port.
Syntax:
public
static
RemoteException

Registry

getRegistry(String

host,

int

port)

throws

where,
host: is a String representing the host name where the registry is running.
Registry: is a reference to the remote object registry for the specified host on port number

1099.

port: is an integer which specifies the port number to use.

Code Snippet 16 shows how to retrieve a reference of the remote object registry of the specified host
and port.
Code Snippet 16:
Registry registry;
String name = “rmi://localhost:1099/HelloServer”;
try {
// Create an instance of the implementation class
HelloServerImpl remoteObject = new HelloServerImpl();
// Retrieve the registry

V 1.0 © Aptech Limited

Concepts

final int PORT = 5000;

Session

9
Remote Method Invocation

registry = LocateRegistry.getRegistry(name, PORT);
// Rebind the remote object with a new name in the registry
Naming.rebind(name, remoteObject);
...
...
} catch (RemoteException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (MalformedURLException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

9.6 exportObject(Remote obj) Method
The exportObject() method is used to export the remote object and make it available to receive
incoming RMI calls using an anonymous port. This method is used if the implementation class does
not extend the UnicastRemoteObject class. The user need to explicitly export the remote object to
accept the incoming RMI calls.
Syntax:
public static RemoteStub exportObject(Remote obj) throws RemoteException

where,
obj: is the remote object to be exported .
RemoteStub: is an object of the RemoteStub, and represents the remote object stub.

Code Snippet 17 shows how to export a remote object.
Code Snippet 17:
Registry registry;
String name = “rmi://localhost:1099”;
try {

Concepts

// Create an instance of the implementation class

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

// This class does not extend the UnicastRemoteObject class
// The user should explicitly export the remote object
HelloServerImpl_ remoteObject = new HelloServerImpl_();
// Retrieve the registry
registry = LocateRegistry.getRegistry(name);
// Export the remote object
UnicastRemoteObject.exportObject(remoteObject);
System.out.println(“Remote object successfully exported.”);
} catch (RemoteException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (NoSuchObjectException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

9.6.1 unexportObject(Remote obj, boolean force) Method
The unexportObject() method is used to remove the remote object from the runtime. If this method
succeeds in un-exporting the remote object, then the remote object cannot accept incoming RMI calls.
The remote object can also be forcibly exported even if there are pending calls to the remote object, or
the remote object has RMI calls in progress.
Syntax:
public static boolean
NoSuchObjectException

unexportObject(Remote

obj,

boolean

force)

throws

where,
obj: is the remote object to be unexported.
force: is a boolean value if true, then unexports the remote object even if there are pending or

in-progress calls. If it is false, then it only unexports the remote object if there are no pending or
in-progress calls.
Code Snippet 18:
Registry registry;
String name = “rmi://localhost:1099”;
try {
// Create an instance of the implementation class

V 1.0 © Aptech Limited

Concepts

Code Snippet 18 shows how to unexport a remote object.

Session

9
Remote Method Invocation

HelloServerImpl remoteObject = new HelloServerImpl();
// Retrieve the registry
registry = LocateRegistry.getRegistry(name);
// Bind the remote object with a name in the registry
registry.rebind(“HelloServer”, remoteObject);
...
...
// Unexport the remote object to stop accepting RMI calls
UnicastRemoteObject.unexportObject(remoteObject);
System.out.println(“Remote object successfully unexported.”);
} catch (RemoteException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (NoSuchObjectException ex) {
System.out.println(“Exception : “ + ex.getMessage());

Concepts

}

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

9.7 Check Your Progress
Which of the following statements about RMI are true?
A.
B.
C.
D.
E.

A Java application can only invoke the methods of the classes available inside its JVM.
Distributed computing revolves around client-server technology.
RMI does not allow a Java program running inside a JVM to execute a method of a class
available in another JVM.
Java provides the java.rmi package which contains all the necessary classes and
interfaces to support distributed computing in Java.
It is not possible for client and server applications, using RMI and running on different
machines, to communicate amongst themselves

(A) A, B, and D
(B) C, D, and E
2.

(C)
(D)

Which of the following statements about RMI are false?
A.
B.
C.
D.
E.

Socket Programming can serialize and transmit objects.
RMI takes into account the byte order during serializing
Socket Programming is a low level technology.
Windows and UNIX have the same byte order in the machine architecture.
RMI does not allow you to serialize and transmit objects.

(A) B and C
(B) D and E
3.

(C)
(D)

A and D
C and D

Can you match the descriptions against features of RMI architecture?
(A)
(B)
(C)
(D)
(E)

Features
Stub and Skeleton Layer
Remote Reference Layer
Transport Layer
Marshalling
Unmarshalling

(A) A-5, B-3, C-4, D-1, E-2
(B) A-3, B-5, C-1, D-2, E-4
4.

A, B, and D
A, C, and D

(1)
(2)
(3)
(4)
(5)

Description
Sets the connections
Converting data into on-the-wire format
Transmitting and receiving data
Converting on-the-wire format into data
Invocation of the remote method.
(C)
(D)

A-5, B-3, C-1, D-2, E-4
A-2, B-3, C-1, D-4, E-5

Which of the following statements about components of RMI are true?
A. The java.rmi.Remote interface serves to distinguish interfaces which are nonremote.
B. A RMI application has to expose methods, which remote clients can invoke.

V 1.0 © Aptech Limited

Concepts

1.

Session

9
Remote Method Invocation
C. java.rmi.Remote is a marker interface.
D. The skeleton resides on the client side.
E. The stub resides on the server side.
(A) A, B, and C
(B) A, B, and C

5.

(C)
(D)

A, B, and D
A, C, and D

You are trying to provide implementation of the remote method String sayHello(String name)
from the HelloInterface. Which of the options will help you to achieve this?
A. public class HelloServerImpl extends UnicastRemoteObject implements
HelloInterface {

public String sayHello(String name) throws RemoteException {
return “Hello “ + name; }

B.

}
public class HelloServerImpl extends UniCastRemoteObject implements
HelloInterface {
public String sayHello(String name) throws RemoteException {
return “Hello “ + name; }

C.

}
public class HelloServerImpl implements UnicastRemoteObject extends
HelloInterface {
public String sayHello(String name) throws RemoteException {
return “Hello “ + name;}

D.

}
public class HelloServerImpl extends UnicastRemoteObj implements
HelloInterface {
public String sayHello(String name) throws RemoteException {
return “Hello “ + name; }

Concepts

}

V 1.0 © Aptech Limited

9

Session
6.

Remote Method Invocation

You are trying to bind the remote object in the rmi registry. Which of the options will help you to
achieve this?
A. String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();

B.

Naming.rebind(name);
String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();

C.

Naming.rebind(remoteObject);
String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();

D.

Naming.rebind(name, remoteObject);
String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();

Concepts

Naming.rebind(name,remoteObject);

V 1.0 © Aptech Limited

Session

9
Remote Method Invocation

9.7.1 Answers
A
A
B
B
A
D

Concepts

1.
2.
3.
4.
5.
6.

V 1.0 © Aptech Limited

9

Session

Remote Method Invocation

Summary
RMI allows a Java program running inside a JVM to execute a method of a class available in
another JVM.

Remote Method Invocation allows Java applications to support the distributed computing
architecture through the use of client-server technology.

The Remote Method Invocation (RMI) is based on a three layered architecture. The three layers of
the RMI architecture are Stub and Skeleton Layer, Remote Reference Layer and Transport Layer.

To implement RMI, you should first identify all the methods which are meant to be remotely
invoked by remote clients so that you can create a remote interface.

The remote class is the implementation class which implements the remote interface.

The getRegistry() method is used to retrieve a reference of the remote object registry on the
specified host name, and the default registry port 1099.

Concepts

V 1.0 © Aptech Limited

Session 10
JavaMail
Welcome to the Session, JavaMail.
This session introduces the JavaMail API. The session explains about
the protocols that can be used to implememnt the e-mail system using
JavaMail API. Futher, the session explains how to send and receive emails.
The session also covers how to reply to an e-mail and send attachments.
In this Session, you will learn to:

Describe the JavaMail API

Describe the various mail protocols

Explain the concept of a Session

Describe how to create a Message

Identify the steps for creating and sending a message

Discuss the steps required for reading a message

Discuss the steps required for replying to a message

Session

10
JavaMail

10.1 Introduction to JavaMail APIs
Java provides a platform independent and a protocol independent API named JavaMail which is used to
compose, read, and write mails through Java application.
The JavaMail API is not a part of the core package. It is a standard extension and has to be downloaded
separately. With JavaMail API you can create programs of type Mail User Agent (MUA). An MUA is a
program that allows you to send and receive email messages. It is generally called an e-mail program or
e-mail client. Some of the examples of MUA are Microsoft Outlook or Eudora. Yahoo and Hotmail are
examples of Web-based MUAs.
The core classes of JavaMail API are available in the package namely, javax.mail and javax.mail.
Internet. The javax.mail package provides commonly used classes in all mail systems. The javax.
mail.Internet package provides classes that are specific to Internet standards such as Multipurpose
Internet Mail Extensions (MIME), Simple Mail Transfer Protocol (SMTP), Post Office Protocol version 3
(POP3), and Internet Message Access Protocol (IMAP) based on specific mail system.

10.1.1 Use of JavaMail
The JavaMail API is not responsible for the actual transporting, delivering, and forwarding messages.
That is the responsibility of Mail Transfer Agent (MTA) type of programs. MTA is a computer program or
software agent that transfers electronic mail messages from one computer to another. The MUA type of
program depends on the MTA types to handle the actual delivery.
The main use of JavaMail API is that it provides a platform independent interface to different service
providers providing their own messaging system.

Concepts

Figure 10.1 shows the use of JavaMail API to manage mails on the mailing system.

Figure 10.1: Managing Mails Using JavaMail API

10.1.2 JavaMail Architetcure
The Java application uses JavaMail API to compose, send, and receive mails independent of the underlying
protocol. The JavaMail API interacts with Service Provider Interface (SPI) to send and receive mails.
Further, the SIP provides implementation of the specific protocol, such as SMTP, POP, IMAP, and so on.
V 1.0 © Aptech Limited

Session

10
JavaMail

It acts as a provider to email service for the Java application.
Figure 10.2 shows the JavaMail architecture.

Figure 10.2: JavaMail Architecture

10.1.3 Mail Protocols
The JavaMail API uses several mail protocols. To understand the JavaMail, you have to understand
the basics of these mail protocols.
The various mail protocols used with JavaMail are:

SMTP

POP
POP is the Post Office Protocol. The current version of POP is version 3; hence, it is referred to as
POP3. This protocol is used for receiving email. The POP3 supports a single mailbox for each user;
all the mails are sent to this mailbox.

V 1.0 © Aptech Limited

Concepts

SMTP is Simple Mail Transfer Protocol. This protocol is used for delivery of email. When you use the
JavaMail API in your mail based program, the program communicates with the SMTP server of
the Internet Service Provider (ISP). This SMTP server is responsible for delivering the email message
to the SMTP server of the recipient.

Session

10
JavaMail

IMAP
IMAP is Internet Message Access Protocol. This protocol is used for receiving email and is a more
advanced protocol. The current version of IMAP is 4; hence, it is referred to as IMAP4. The IMAP4
supports multiple folders for each user and they can be shared by multiple users.

MIME
MIME is Multipurpose Internet Mail Extensions. This protocol is not used for sending or receiving
mail, it defines the content type of the message transferred. This protocol also defines the format
of the messages and attachments. The content types are text/plain or text/html. The format
includes headers like sender, recipient, subject.

Note - The main difference between POP3 and IMAP is that:

POP3 - Supports a single mailbox folder whereas IMAP supports multiple folders for each user.
MIME - If the content type is text/plain then the receiver program simply displays the text without any
processing. However, if the content type is text/html, then the receiving program has to expand the
html tag and then display the output contents.

10.2 JavaMail API
The JavaMail API defines three main classes namely, Session, Message, and Transport. These classes
model the mail system.

10.2.1 Session
In the context of a mailing system, a session is a lasting connection between a user and a host, usually a
server. Session starts when the service is first provided and closes when the service is ended. A user may
have multiple active sessions simultaneously. A session represents the complete state of a service.
The javax.mail package provides a class Session to define a basic mail session. Once a session is
made available, it is through this session that all subsequent operations of mailing system are carried
out.

10.2.2 Methods of Session
Concepts

The javax.mail.Session has static methods to create sessions. The java.util.Properties class
object is used to provide initial information like mail server, user name, and password.
The Session class provides the following two methods to create a session:

public static Session getInstance()

The method creates a session object based on the initial values provided in the Properties object.
The JavaMail specification specifies that the following properties - mail.store.protocol,
mail.transport.protocol, mail.host, mail.user, and mail.from should be specified in
the Properties object.
V 1.0 © Aptech Limited

Session

10
JavaMail

Syntax:
public static Session getInstance(Properties prop)

where,
prop: Is an object of the Properties class.
Session: Returns a new Session object.

Code Snippet shows how to create a session with the getInstance() method.
Code Snippet 1:
String mailhost = “gmail.websolutions.com”;
// Retrieve the system properties
Properties props = System.getProperties();
// Specify the host name of the SMTP
props.put(“mail.smtp.host”, mailhost);
// Get a Session object
Session session = Session.getInstance(props);

public static Session getDefaultInstance()

The method returns a default session object. If a default session object is not available, it creates
a new one, installs it as the default and then returns it. The JavaMail specification specifies that
the following properties - mail.store.protocol, mail.transport.protocol, mail.host,
mail.user, and mail.from should be specified in the Properties object.
Syntax:
public static Session getDefaultInstance(Properties prop)

where,
prop: Is an object of the Properties class.
Session: Returns the default Session object, or a new one if default is not available.

Code Snippet 2:
String mailhost = “gmail.websolutions.com”;
// Retrieve the system properties
Properties props = System.getProperties();

V 1.0 © Aptech Limited

Concepts

Code Snippet 2 shows how to retrieve a default session object with the getDefaultInstance()
method.

Session

10
JavaMail
// Specify the host name of the SMTP
props.put(“mail.smtp.host”, mailhost);
// Get the default Session object
Session session = Session.getDefaultInstance(props);

public static Session getDefaultInstance(Properties prop, Authenticator
auth)

The getDefaultInstance() method is used to retrieve the default Session object. If a default
session is not available a new session object is created and set as a default.
A Properties object is used to specify the properties of the JavaMail specification. The session
object is available to all the code running in the same JVM. The access to the session object has
to be restricted because the session object contains security sensitive information like user name
and password. An object of the Authenticator class is used to check the access permission.
When the session is created, an Authenticator object is passed. This Authenticator object
is compared with the Authenticator object that is passed in subsequent calls to retrieve the
default session. If the objects are not same then the request is denied.
Syntax:
public static Session getDefaultInstance(Properties prop, Authenticator
auth)

where,
prop: Is an object of the Properties class which contains the properties specified by the

JavaMail specification.

auth: Is an object of Authenticator class used to call back to the application to check the

user name and password when required.

Session: Is the return type, and represents the default session object, if one is available or

a newly created session object.

Code Snippet 3 shows how to create an Authenticator object called GMAILAuthenticator.
Code Snippet 3:
import javax.mail.*;

Concepts

import java.net.InetAddress;
// Authenticator for requesting password information
public class GMAILAuthenticator extends Authenticator {
String username;
String password;

V 1.0 © Aptech Limited

Session

10
JavaMail

public GMAILAuthenticator (String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}

Code Snippet 4 shows how to retrieve the default session object with an Authenticator object.
Code Snippet 4:
...
GMAILAuthenticator auth;
String mailhost = “gmail.websolutions.com”;
// Retrieve the system properties
Properties props = System.getProperties();
// Specify the host name of the smtp
props.put(“mail.smtp.host”, mailhost);
try {
// Create the authenticator object with username and password
auth = new GMAILAuthenticator(“mails.vincent@gmail.com”, “vincent”);
// Get a Session object
Session session = Session.getDefaultInstance(props, auth);
...
} catch(Exception ex) {
System.out.println(“Exception : “ + ex.getMessage();
...

public static Session getInstance(Properties prop, Authenticator auth)

The getInstance() method is used to retrieve a new Session object.

V 1.0 © Aptech Limited

Concepts

}

Session

10
JavaMail

Syntax:
public static Session getInstance(Properties prop, Authenticator auth)

where,
prop: Is an object of the Properties class which contains the properties specified by the

JavaMail specification.

auth: Is an object of Authenticator class used to call back to the application to check the

user name and password when required.

Session: Is the return type, and represents the default session object, if one is available or

a newly created session object.

Code Snippet 5 shows how to retrieve a new Session object with an Authenticator object.
Code Snippet 5:
...
GMAILAuthenticator auth;
String mailhost = “gmail.websolutions.com”;
// Retrieve the system properties
Properties props = System.getProperties();
// Specify the host name of the smtp
props.put(“mail.smtp.host”, mailhost);
try {
// Create the authenticator object
auth = new GMAILAuthenticator(“mails.vincent@gmail.com”, “vincent”);
// Get a Session object
Session session = Session.getInstance(props, auth);
...
} catch(Exception ex) {
System.out.println(“Exception : “ + ex.getMessage();

Concepts

}
...

public Properties getProperties()

The getProperties() method is used to retrieve the Properties object associated with the
specified Session object.

V 1.0 © Aptech Limited

Session

10
JavaMail

Syntax:
public Properties getProperties()

where,
Properties: Is the return type, and represents a Properties object containing the
properties associated with the specified Session object.

Code Snippet 6 shows how to retrieve the Properties object associated with the Session
object.
Code Snippet 6:
...
String mailhost = “gmail.websolutions.com”;
// Retrieve the system properties
Properties props = System.getProperties();
// Specify the host name of the smtp
props.put(“mail.smtp.host”, mailhost);
try {
// Get a Session object
Session session = Session.getInstance(props);
...
...
Properties sessionProps = session.getProperties();
System.out.println(“Properties :” + sessionProps);
} catch(Exception ex) {
System.out.println(“Exception : “ + ex.getMessage();
}
...
public String getProperty(String name)

The getProperty() method is used to retrieve the value of the specified property name associated
with the session object. The method returns a null value if there are no properties.
Syntax:
public String getProperty(String name)

where,

V 1.0 © Aptech Limited

Concepts

Session

10
JavaMail
name: Is a String object which specifies the property name to retrieve.

Code Snippet 7 shows how to retrieve the value of the specified property name associated with the
session object.
Code Snippet 7:
...
String mailhost = “gmail.websolutions.com”;
// Retrieve the system properties
Properties props = System.getProperties();
// Specify the host name of the smtp
props.put(“mail.smtp.host”, mailhost);
props.put(“mail.transport.protocol”, “smtp”);
props.put(“mail.smtp.port”, “25”);
try {
// Get a Session object
Session session = Session.getInstance(props);
...
...
String strHost = session.getProperty(“mail.smtp.host”);
System.out.println(“Mail Host : “ + strHost);
String strProtocol = session.getProperty(“mail.transport.
protocol”);
System.out.println(“Mail Protocol : “ + strProtocol);
String strPort = session.getProperty(“mail.smtp.port”);
System.out.println(“Mail Port : “ + strPort);
} catch(Exception ex) {
System.out.println(“Exception : “ + ex.getMessage();

Concepts

}
...

V 1.0 © Aptech Limited

Session

10
JavaMail

10.2.3 Creating a Message
Once a session object is created, you have to create a Message object from that Session object. This
message object can then be sent to a mail recipient. The message object has several parts like address
‘from’, ‘to’, and ‘reply to’, and other parts like ‘date’ and ‘subject’.
The javax.mail.Message is an abstract class and is not used directly; its subclass which provides
concrete implementation is used.
The javax.mail.Message class implements a Part interface which specifies the attributes and
content type of the message.

10.2.4 Methods of the Message Class
Some of the methods of the Message class are as follows:

setReplyTo(Address[] addresses)

getAllRecipients()

The methods are described as follows:

setReplyTo(Address[] addresses)

The setReplyTo() method is used to set the ‘Reply-To’ field of the message. If the argument
address is null, then the ‘Reply-To’ header is removed from the message.
Syntax:
public void setReplyTo(Address[] addresses) throws MessagingException

where,
addresses: Is an array of the Address class which contains the addresses to which the

message is to be directed.

Code Snippet 8 shows how to set the addresses of the ’Reply-To’ header.
Code Snippet 8:
...
...
Address[] addresses = {new InternetAddress(“mike@gmail.com”), new
InternetAddress(“alex@gmail.com”) };
Session session = Session.getInstance(props, null);

V 1.0 © Aptech Limited

Concepts

try {

Session

10
JavaMail
// Construct the message
Message msg = new MimeMessage(session);
// Set the addresses of “Reply-To” header
msg.setReplyTo(addresses);
...
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}
...

public Address[] getAllRecipients()

The getAllRecipients() method is used to retrieve all the recipient addresses of the message.
The getAllRecipients() method extracts the address of ‘TO’, ‘CC’, and ‘BCC’ recipients. The
method returns a null value, if recipient headers are not present in the message. If recipient header
is present, but does not contain any addresses, then the method might return an empty array.
Syntax:
public Address[] getAllRecipients() throws MessagingException

where,
Address[]: Is an array of objects of Address class and represents all the recipients

addresses.

Code Snippet 9 shows how to retrieve the addresses of all recipients.
Code Snippet 9:
...
String strFrom = “mails.vincent@gmail.com”;

Concepts

String strTo = “mails.mike@gmail.com”;
String strCc = “alex@gmail.com”;
String strBcc = “john@gmail.com”;
try {
// Retrieve the session instance with the desired attributes
Session session = Session.getInstance(props, null);

V 1.0 © Aptech Limited

Session

10
JavaMail

// Construct the message
Message msg = new MimeMessage(session);
// Set the sender of the message
msg.setFrom(new InternetAddress(strFrom));
// Set the TO recipient of the message
msg.setRecipients(Message.RecipientType.TO, InternetAddress.
parse(strTo,false));
// Set the CC recipient of the message
msg.setRecipients(Message.RecipientType.CC, InternetAddress.
parse(strCc, false));
// Set the BCC recipient of the message
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.
parse(strBcc, false));
// Retrieve all the recipients addresses
Address[] recipientAddresses = msg. getAllRecipients();
for(int i = 0; i < recipientAddresses.length; i++) {
System.out.println(“Addresses are : “ + recipientAddresses[i]);
}
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}
...

The javax.mail.internet.MimeMessage class is a subclass of the Message class and is used
to create a Message object. This message object represents a MIME style email message. To create a
message object, you first create an empty MimeMessage object and then set the appropriate attributes
and contents.

V 1.0 © Aptech Limited

Concepts

10.2.5 How to Use MimeMessage

Session

10
JavaMail

Create an empty message object from a session
Create a MimeMessage using the constructor which takes a Session object as an argument. The
session object should be a valid session created earlier with a Session class.
Syntax:
public MimeMessage(Session session)

where,
session: Is a valid Session object created using the properties.

Code Snippet 10 shows how to create a Message object from a valid session.
Code Snippet 10:
/* To handle the SSL (Secured Socket Layer) provide security provider, the
addProvider() method adds a security provider */
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.
Provider());
// Retrieve the system properties
java.util.Properties props = System.getProperties();
// Initialize string with the host IP address
String strHost = “pop.gmail.com”;
/* Assign the attribute mail.smtp.host with the value contained in the
variable strHost */
props.put(“mail.smtp.host”, strHost);
// Assign the attribute mail.transport.protocol as smtp
props.put(“mail.transport.protocol”, “smtp”);
// Assign the attribute mail.smtp.port as 25
props.put(“mail.smtp.port”, “25”);
try {
Session session = Session.getInstance(props, null);

Concepts

// Construct the message
Message msg = new MimeMessage(session);
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited

Session

10
JavaMail

Set the attributes required
Several attributes are required to be set once a message object is created. These attributes include
the sent date, subject of the message, address from and to, additional address for cc and bcc and
attachments.
Syntax:
public void setFrom(Address address)

where,
address: Is an object of the class Address representing the sender address.

Code Snippet 11 shows how to set some of the attributes of the Message object.
Code Snippet 11:
String strFrom = “mails.vincent@gmail.com”;
String strTo = “mails.mike@gmail.com;
String strSubject = “Hi Mike”;
String strText = “Hello Mike, how are you”;
try {
// Set the sender of the message
msg.setFrom(new InternetAddress(strFrom));
// Set the recipient of the message
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(strTo, false));
//Set the subject of the message
msg.setSubject(strSubject);
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

Set the content type of the message
The default content type with MimeMessage is ‘text/plain’. If the content type is not plain
text, then the content type of the message needs to be set.
Syntax:
public
void
MessagingException

setContent(Object

V 1.0 © Aptech Limited

content,String

type)throws

Concepts

Session

10
JavaMail

where,
content: Is generally a String which contains the message contents.
type: Is a String which specifies a MIME type.

Code Snippet 12 shows how to set the content type with an HTML based message.
Code Snippet 12:
String strHTMLText = “<html><b>Hello Mike, how are you… </b></html>”;
try {
// Set the content type of the message
msg.setContent(strHTMLText,”text/html”);
}catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

Set content of a message
The contents of the message can be set by the setContent() or setText() method. The
setContent() method allows to set both the content and its type. The setText() method is
used to set only plain text to the message.
Syntax:
public void setText(java.lang.String text) throws MessagingException

where,
text: Is a String specifying the contents of the message in plain text.

Code Snippet 13 shows how to set plain text of a message using the setText() method.
Code Snippet 13:
try {
// Set the text of the message to plain

Concepts

msg.setText(strText);
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited

Session

10
JavaMail

10.2.6 Determining Size of a Message
The getSize() method is used to retrieve the size of the message contents in bytes. If the size of the
message contents cannot be determined a value of -1 is returned. The getSize() method may not
return the exact size of the contents if the message has encoded contents.
Syntax:
public int getSize() throws MessagingException

where,
int: is an integer specifying the size of the message contents. If the size cannot be determined a
value of -1 is returned.

Code Snippet 14 shows how to retrieve the number of new messages in the folder.
Code Snippet 14:
...
String strHost =”10.1.1.23”;
String strUser = “johnk@aptech.ac.in”;
String strPass = “ WinJohn400”;
int openMode;
Store store;
try {
// Retrieve the session instance with the desired attributes
Properties props = System.getProperties();
props.put(“mail.pop3.host”, strHost);
Session session = Session.getInstance(props);
// Construct the message

Concepts

Message msg = new MimeMessage(session);

V 1.0 © Aptech Limited

Session

10
JavaMail

Folder folder = null;
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
if (store != null) {
folder = store.getDefaultFolder()
if (folder == null) throw new Exception(“No default folder”);
// Retrieve the INBOX folder
folder = folder.getFolder(“INBOX”);
// Open the folder in read only mode
folder.open(Folder.READ_ONLY);
// Retrieve the open mode
openMode = folder.getMode();
if (openMode == Folder.READ_ONLY) {
System.out.println(“Open mode : READ_ONLY”);
}
// Retrieve the number of new messages
int newMessages = folder.getNewMessageCount();

10.2.7 Concept of Address

Concepts

The address is an Internet email address of a user for a specific domain. Generally the address is of the
form user@host.domain. When you use the services of a mailing system like yahoo or rediff, you have
to create an account with this service provider. This account is to identify one user from another, and is
unique for each user. In the address the user name has to be unique, followed by a @ sign, the host is
the service provider like yahoo. The domain identifies the type organization for example .com represents
commercial organization, .edu represents educational institution and so on.

V 1.0 © Aptech Limited

Session

10
JavaMail

Figure 10.3 displays the concept of address.

Figure 10.3: Concept of Address

10.2.8 Creating Address
The javax.mail provides an Address class which is an abstract class. Generally a subclass which
provides a concrete implementation is used to create an address. This address is required by the message
class object to specify the parts like sender and its recipients.
The javax.mail.internet.InternetAddress is generally used to create the address required for
sender and its recipients. The InternetAddress is a subclass of javax.mail.Address class.
To create an InternetAddress instance, use one of the ways:

Constructors
The constructors are generally used to create a single Internet address. Generally, these are used
to create the address of the sender.
Syntax:
public InternetAddress(String address) throws AddressException

where,
address: is a String representing the email address in the form “user@host.domain”
address,

boolean

strict)throws

where,
address: is a String representing the email address in the form “user@host.domain”
strict: is a boolean variable, if true detailed syntax of the address is checked.

V 1.0 © Aptech Limited

Concepts

public
InternetAddress(String
AddressException

Session

10
JavaMail

Code Snippet 15 shows how to create an address using the one argument constructor.
Code Snippet 15:
String strFrom = “mails.vincent@gmail.com”;
try {
InternetAddress fromAddress = new InternetAddress(strFrom);
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

parse() method
The static method parse() is generally used to parse several address separated by commas. When
you send or reply to a mail there can be several recipients. Comma delimited email addresses
are provided in To, Cc and Bcc. This method returns an array of addresses by parsing the string
containing the addresses.
Syntax:
public
static
InternetAddress[]
AddressException

parse(String

addressList)

throws

where,
addressList: is a String representing a comma delimited list of email addresses.
InternetAddress[]: is an array of InternetAddress class, containing the Internet

address from the address list.

Code Snippet 16 shows how to parse a comma delimited list of addresses to create an array of
InternetAddress class.
Code Snippet 16:
String strCc = “mails.mike@gmail.com, fred@gmail.com, mike@gmail.com”;
try {
InternetAddress[] ccAddress = InternetAddress.parse(strCc,

Concepts

false);
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited

Session

10
JavaMail

10.2.9 Concept of Transport Class
Once the message object is created and its required attributes are set, the final step involves sending
the message. The javax.mail.Transport class is used to send the message to all its recipients. The
javax.mail.Transport is an abstract class. This class has static methods to send messages to all
the recipients. The Transport class static methods throw a SendFailedException exception if any
of the recipient address is found to be invalid. Successful sending of the message to its recipients does
not imply that the message has reached its ultimate recipient. Failures can still occur in the later stages
of delivery.
Figure 10.4 displays the concept of Transport class.

Figure 10.4: Concept of Transport Class

10.2.10 Methods of Transport Class
To send a message to its recipients use one of the following static methods of the Transport class:

send(Message msg)

The method takes one argument, an object of the Message class, and sends the message to all the
recipients specified in the message object.
Syntax:
public static void send(Message msg) throws MessagingException
msg: is an object of the Message class.

V 1.0 © Aptech Limited

Concepts

where,

Session

10
JavaMail

Code Snippet 17 shows how to send a message to all its recipients.
Code Snippet 17:
try {
Session session = Session.getInstance(props, null);
// Construct the message
Message msg = new MimeMessage(session);
// Set the sender of the message
msg.setFrom(new InternetAddress(strFrom));
// Set the recipients of the message
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(strTo, false));
//Set the subject of the message
msg.setSubject(strSubject);
// Set the text of the message
msg.setText(strText);
// Send the message to the recipients
Transport.send(msg);
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());}

send(Message msg, Address[] addresses)

The method takes two arguments, an object of the Message class, and an array of Address class.
This method sends the message to the addresses in the array specified. The method ignores all the
addresses of recipients in the message object.

Concepts

Syntax:
public static void
MessagingException

send(Message

msg,

where,
msg: is an object of the Message class.

V 1.0 © Aptech Limited

Address[]

addresses)

throws

Session

10
JavaMail

addresses: is an array of Address class containing address of all recipients.

Code Snippet 18 shows how to send a message to all the recipients from an Address array.
Code Snippet 18:
Address[] addresses = {new InetAddress(“mike@gmail.com), new
InetAddress(“mike@gmail.com), };
try {
Session session = Session.getInstance(props, null);
// Construct the message
Message msg = new MimeMessage(session);
// Set the sender of the message
msg.setFrom(new InternetAddress(strFrom));
// Set the recipients of the message
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(strTo, false));
// Set the subject of the message
msg.setSubject(strSubject);
// Set the text of the message
msg.setText(strText);
// Send the message to the recipients
Transport.send(msg, addresses);
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

A mail service provider maintains a store which contains the folder where your messages are kept. To
retrieve a message from email service, you have to gain access to the store first. The POP3 protocol
maintains its own store. Similarly, the IMAP maintains its own store.
Once you have created a session object, you gain access to the store by specifying the protocol. The
Session class has a method getStore() which takes one argument, the protocol implemented by the
store you want to gain access. The store object returned by the getStore() method is used to establish

V 1.0 © Aptech Limited

Concepts

10.2.11 Store

Session

10
JavaMail

a connection with your user id and password.

10.2.12 Accessing Message Store
The javax.mail.Store class represents a message store and the access protocol, for storing and
retrieving messages.
To gain access to the message store perform the following steps:

Retrieve the Store object from session
The getStore() method of the Session class is used to retrieve Store object. This method takes
one argument, String (POP3 or IMAP protocol).
Syntax:
public Store getStore(String protocol) throws NoSuchProviderException

where,
protocol: is a String specifying the protocol, valid values are POP3 and IMAP.
Store: is the return type which represents a store object.

Code Snippet 19 shows how to retrieve the store object from a session.
Code Snippet 19:
// Retrieve the system properties
Properties props = System.getProperties();
// Assigns the mail.transport.protocol attribute as pop3
props.put(“mail.transport.protocol”, “pop3”);
// Set the port to 995
props.setProperty(“mail.pop3.port”, “995”);
// Retrieve the system properties
Properties props = System.getProperties();
// Assigns the mail.transport.protocol attribute as pop3

Concepts

props.put(“mail.transport.protocol”, “pop3”);
// Set the port to 995
props.setProperty(“mail.pop3.port”, “995”);
try {
// Retrieve the session instance

V 1.0 © Aptech Limited

Session

10
JavaMail

Session session = Session.getInstance(props);
// Retrieve the store
store = session.getStore(“pop3”);
} catch(NoSuchProviderException ex) {
System.out.println(“Exception : “ + ex.getMessage());

Connect to the mail host with authentication
The Store class inherits the method connect() from the super class Service. The connect()
method is used to establish a connection with the mail host. To get a connection to the store you
pass the authentication parameters user id and password.
Syntax:
public void connect(String
MessagingException

host,String

user,String

password)throws

where,
host: is a String which specifies the mail host.
user: is a String which specifies the user id.
password: is a String which specifies the password.

Code Snippet 20 shows how to connect to the mail host.
Code Snippet 20:
String strHost = “pop.gmail.com”;
String strUser = “mails.vincent@gmail.com”;
String strPass = “vincent”;
// Retrieve the system properties
Properties props = System.getProperties();
// Assign the mail.transport.protocol attribute as pop3
props.put(“mail.transport.protocol”, “pop3”);
props.setProperty(“mail.pop3.port”, “995”);
try {
// Retrieve the session object with properties
Session session = Session.getInstance(props);
// Retrieve the store

V 1.0 © Aptech Limited

Concepts

// Set the port to 995

Session

10
JavaMail
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());

10.2.13 Folder
Folder is the namespace where your messages are available. For the protocol POP3 there is only one
folder INBOX. The IMAP protocol supports multiple folders. Once Store object is connected you can
retrieve the folder. The messages are then retrieved from the folder. The Folder class represents a
folder for the message. Folders can contain other folders, or messages or both. The folder names are

implementation dependent. The “INBOX” folder is a reserved word and it means that this is the primary
folder for use on this server. All Store class might not provide an “INBOX” folder. All users might not also
have an “INBOX” folder at all times.
The create() method is used to create a folder and the exists() method is used to check whether a
folder exists or not. Initially a Folder is in closed state but can be opened using the open() method.
Some of the methods of the Folder class are as follows:

getMode()

getNewMessageCount()

The methods are discussed in details.

public int getMode()

The getMode() method is used to retrieve the open mode of the folder. The mode specifies
whether the folder supports “ready-only” or “read-write” operations. If the open mode cannot be
determined a value of -1 is returned.
Syntax:
public int getMode()

Concepts

where,
int: is an integer which specifies the open mode of the folder. The valid values are Folder.
READ_ONLY and Folder.READ_WRITE.

V 1.0 © Aptech Limited

Session

10
JavaMail

Code Snippet 21 shows how to retrieve the open mode of the folder.
Code Snippet 21:
...
String strHost =”10.1.1.23”;
String strUser = “johnk@aptech.ac.in”;
String strPass = “WinJohn400”;
int openMode;
Store store;
try {
// Retrieve the session instance with the desired attributes
Properties props = System.getProperties();
props.put(“mail.pop3.host”, strHost);
Session session = Session.getInstance(props);
// Construct the message
Message msg = new MimeMessage(session);
Folder folder = null;
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
if(store != null) {
folder = store.getDefaultFolder();
if(folder == null) throw new Exception(“No default folder”);
// Retrieve the INBOX folder
folder = folder.getFolder(“INBOX”);
folder.open(Folder.READ_ONLY);
// Retrieve the open mode
openMode = folder.getMode();
if (openMode == Folder.READ_ONLY) {

V 1.0 © Aptech Limited

Concepts

// Open the folder in read only mode

Session

10
JavaMail
System.out.println(“Open mode : READ_ONLY”);
}
}
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
}
...

Note - The values of variables strHost, strUser, strPass should be replaced with the login details of the

POP3 mail server for which the user has access.

public int getNewMessageCount() throws MessagingException

The getNewMessageCount() method is used to retrieve the number of new messages in the
folder. Some implementations of the folder may not support this operation because it is a costly
operation, in which case a -1 is returned.
Syntax:
public int getNewMessageCount() throws MessagingException

where,
int: is an integer which specifies the number of new messages in the folder.

Code Snippet 22 shows how to retrieve the number of new messages in the folder.
Code Snippet 22:
...
String strHost =”10.1.1.23”;

Concepts

String strUser = “johnk@aptech.ac.in”;
String strPass = “WinJohn400”;
int openMode;
Store store;
try {
// Retrieve the session instance with the desired attributes

V 1.0 © Aptech Limited

Session

10
JavaMail

Properties props = System.getProperties();
props.put(“mail.pop3.host”, strHost);
Session session = Session.getInstance(props);
// Construct the message
Message msg = new MimeMessage(session);
Folder folder = null;
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
if(store != null) {
folder = store.getDefaultFolder();
if(folder == null) throw new Exception(“No default folder.”);
// Retrieve the INBOX folder
folder = folder.getFolder(“INBOX”);
// Open the folder in read only mode
folder.open(Folder.READ_ONLY);
// Retrieve the open mode
openMode = folder.getMode();
if (openMode == Folder.READ_ONLY) {
System.out.println(“Open mode : READ_ONLY”);
}
} catch (Exception ex) {
ex.printStackTrace();
}

To read a message from the folder, perform the following steps:

Retrieve the default folder
The Store class has a method getDefaultFolder() which returns the reference to the default
folder. The default folder is an object of the Folder class.

V 1.0 © Aptech Limited

Concepts

...

Session

10
JavaMail

Syntax:
public abstract Folder getDefaultFolder() throws MessagingException

where,
Folder: is an object of the class Folder which represents the default folder.

Code Snippet 23 shows how to retrieve the default folder.
Code Snippet 23:
try {
Folder folder;// Retrieve the session object with properties
Session session = Session.getInstance(props);
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
if (store != null) {
// Retrieve the default folder
folder = store.getDefaultFolder();}
}
catch(MessagingException ex)
{
System.out.println(“Exception : “ + ex.getMessage());
}

From the default folder retrieve the INBOX folder
The Folder class has the method getFolder() to retrieve the named folder; in case of POP3 it
is INBOX.

Concepts

Syntax:
public abstract Folder getFolder(String name) throws MessagingException

where,
name: is a String which represents the folder name like INBOX.

V 1.0 © Aptech Limited

Session

10
JavaMail

Code Snippet 24 shows how to retrieve the named folder like INBOX.
Code Snippet 24:
try {
Folder folder;
// Retrieve the session object with properties
Session session = Session.getInstance(props);
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
if (store != null) {
// Retrieve the default folder
folder = store.getDefaultFolder();
// Retrieve the INBOX folder
folder = folder.getFolder(“INBOX”);
}
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

Open the INBOX folder
Once you have the reference of the named folder like INBOX, you use the open() method of the
folder with the desired mode. The mode specifies whether you can only read from the folder, or
perform both read and write operations.
Syntax:
public abstract void open(int mode) throws MessagingException
mode: is an integer which specifies the mode of operation, valid values are Folder.READ_
ONLY or Folder.READ_WRITE.

V 1.0 © Aptech Limited

Concepts

where,

Session

10
JavaMail

Code Snippet 25 shows how to open the named folder like INBOX with read only mode.
Code Snippet 25:
try {
Folder folder;
// Retrieve the session object with properties
Session session = Session.getInstance(props);
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
if (store != null) {
// Retrieve the default folder
folder = store.getDefaultFolder();
// Retrieve the INBOX folder
folder = folder.getFolder(“INBOX”);
// Open the folder in read only mode
folder.open(Folder.READ_ONLY);
}
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

Retrieve the messages
Once the folder is opened you can retrieve messages with the getMessages() method of the
Folder class. This method returns an array of Message class, which contains your messages.
Syntax:

Concepts

public Message[] getMessages() throws MessagingException

where,
Message: is an array of the Message class containing the messages.

V 1.0 © Aptech Limited

Session

10
JavaMail

Code Snippet 26 shows how to retrieve the messages from the folder and print the subject of the
message.
Code Snippet 26:
try {
// Retrieve the messages from the folder
Message[] msgs = folder.getMessages();
for (int i = 0; i < msgs.length; i++) {
String subject = msgs[i].getSubject();
System.out.println(“Subject : “ + subject);
}
} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage()); }

10.2.14 Exception Class
Several exceptions are thrown while using the JavaMail API. Some of the important exceptions are:

NoSuchProviderException

This exception is generated if a provider for the given protocol is not found.

MessagingException

This exception is generated if a folder could not be located or created. This is the base class for all
messaging exceptions.

AddressException

This exception is generated if the specified address cannot be parsed to create a valid
InternetAddress.

SendFailedException

Concepts

This exception is raised if the message cannot be sent to any of the recipients.

V 1.0 © Aptech Limited

Session

10
JavaMail

10.3 Creating a Message and Mailing
To create and send a message using JavaMail API, perform the steps:

Create and initialize a Properties object.

Create a Session object with the initialized properties.

Create a Message object from the session.

Set the various attributes of the message.

Send the message with a Transport object.

Figure 10.5 displays the creating message and mailing.

Figure 10.5: Creating Message and Mailing
Code Snippet 27 shows how to create and send a message.
Code Snippet 27:
String strHost = “pop.gmail.com”;

Concepts

String strTo = “mike@gmail.com”;
String strFrom = “mails.vincent.com”;
String strCc = “alex@gmail.com”;
String strBcc = “fred@gmail.com”;
String strSubject = “Weekend party”;
String strText = “Hi all, you are all invited to a party this Saturday”;

V 1.0 © Aptech Limited

Session

10
JavaMail

// Retrieve the system properties
java.util.Properties props = System.getProperties();
// Assign the attribute mail.smtp.host as host
props.put(“mail.smtp.host”, strHost);
// Assign the attribute mail.transport.protocol as protocol
props.put(“mail.transport.protocol”, “smtp”);
// Assign the attribute mail.smtp.port as port number
props.put(“mail.smtp.port”, “25”);
try {
// Create the session object
Session session = Session.getInstance(props, null);
// Construct the message object from the session
Message msg = new MimeMessage(session);
// Set the From address
msg.setFrom(new InternetAddress(strFrom));
// Set the To address
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(strTo, false));
// Set the Cc address
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(strCc, false));
// Set the Bcc address
msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(strBcc, false));
// Set the subject of the message
// Set the message text as plain text
msg.setText(strText);
// Set the current date

V 1.0 © Aptech Limited

Concepts

msg.setSubject(strSubject);

Session

10
JavaMail

msg.setSentDate(new Date());
// Send the message to its recipients
Transport.send(msg);
System.out.println(“\nMail was sent successfully.”);
} catch (MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

10.3.1 Reading the Message
To read a message from a folder, perform the steps:

Create and initialize a Properties object

Create a Session object with the initialized properties

Create a Store object

Use the store object to connect to the host

Retrieve the default folder

Retrieve the named folder from the default folder

Open the folder

Retrieve the messages from the folder

Code Snippet 28 shows how to read a message from the INBOX folder.
Code Snippet 28:
JTextField txtName;

Concepts

JPasswordField pswPassword;
String strHost = “pop.gmail.com”;
String strUser = txtUserName.getText().trim();
String strPass = pswPassword.getText().trim();
Store store = null;

V 1.0 © Aptech Limited

Session

10
JavaMail

Folder folder = null;
try {
// Retrieve the system properties
Properties props = System.getProperties();
// Assign the attribute mail.pop3.host as host
props.put(“mail.pop3.host”, strHost);
// Assign the attribute mail.transport.protocol as protocol
props.put(“mail.transport.protocol”, “pop3”);
// Assign the attribute mail.pop3.port as port number
props.put(“mail.pop3.port”, “995”);
// Create the session object
Session session = Session.getInstance(props);
// Retrieve the store
store = session.getStore(“pop3”);
// Establish connection with the mail host
store.connect(strHost, strUser, strPass);
folder = store.getDefaultFolder();
// Retrieve the INBOX folder
folder = folder.getFolder(“INBOX”);
// Open the folder in read only mode
folder.open(Folder.READ_ONLY);
// Retrieve the messages from the folder
Message[] msgs = folder.getMessages();
msgBodies = new String[msgs.length];
for (int i = 0; i < msgs.length; i++) {
String subject=msgs[i].getSubject();
System.out.println(“Subject : “ + subject); }

V 1.0 © Aptech Limited

Concepts

// Retrieve subject of the message

Session

10
JavaMail

} catch (MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage();}

10.3.2 Replying to the Message
To reply to a message, perform the following steps:

Retrieve the messages
To reply to any message you have to first retrieve the messages, and display them in a GUI.

Select the message to reply and edit the text
Once the messages are displayed in the GUI, you have to select a message to reply and edit its
text.

Use the reply() method of Message class
The Message class has a method reply() which returns a new message properly configured to
reply to the sender or all the recipients. This method automatically adds “RE:” to the subject. This
method does not add the original text; you should add the original text which you have edited.
Syntax:
public abstract Message reply(boolean replyAll) throws MessagingException

where,
replyAll: is a boolean. If true reply is sent to all recipients. If false reply is sent to only to

the “To” address.

Message: is an object of class Message which is created as a new Message object and

returned.

Code Snippet 29 shows how to reply to a message.
Code Snippet 29:
try {

Concepts

Message message;
// TextArea to display and edit the message text
JTextArea txaText;
int index;

V 1.0 © Aptech Limited

Session

10
JavaMail

// Retrieve the message and display them in a GUI
...
// Allow to select a message from the GUI and edit the text
message = msgs[index];
// Retrieve the edited text
strText = txaText.getText();
// Reply to the message
MimeMessage reply = (MimeMessage)message.reply(false);
// Set the sender’s address
reply.setFrom(new InternetAddress(“mails.vincent@gmail.com”));
// Set the message
reply.setText(strText);
// Send the message
Transport.send(reply);
} catch(AddressException ex) {
System.out.println(“Exception : ” + ex.getMessage());
} catch(MessagingException ex) {
System.out.println(“Exception : ” + ex.getMessage());

Concepts

}

V 1.0 © Aptech Limited

Session

10
JavaMail

10.4 Check Your Progress
1.

Which of the following statements about JavaMail API are true?
A.
B.
C.
D.
E.
(A)
(B)

2.

3.

The JavaMail API is part of the core package.
The JavaMail API is used to read, compose, and send electronic messages.
The MUA type of program depends on the MTA types to handle the actual delivery.
The JavaMail provides a means to develop protocol-independent access for sending
and receiving mails.
The JavaMail API is responsible for the actual transporting, delivering, and forwarding
messages.
A, B, and C
C, D, and E

(C)
(D)

B, C, and D
A, C, and D

Can you match the descriptions of mail protocols against their features?
(A)
(B)
(C)
(D)
(E)

Feature
SMTP
POP
IMAP
MIME
JavaMail

(A)
(B)

A-4, B-5, C-1, D-2, E-3
A-4, B-5, C-1, D-3, E-2

(1)
(2)
(3)
(4)
(5)

Description
Supports multiple folders for each user
Defines content type of the message
API
Delivering of email
Supports a single mailbox
(C)
(D)

A-5, B-4, C-2, D-3, E-1
A-2, B-3, C-5, D-1, E-4

You are trying to retrieve a default session object. Which of the following options will help you
achieve this?
A. String mailhost = “gmail.websolutions.com”;
Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailhost);

Concepts

B.

Session session = Session.getDefaultInstance(props);
String mailhost = “gmail.websolutions.com”;
Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailhost);
Session session = Session.getInstance(props);

V 1.0 © Aptech Limited

Session
C.

10
JavaMail

String mailhost = “gmail.websolutions.com”;
Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailhost);

D.

Session session = Session.getInstance();
String mailhost = “gmail.websolutions.com”;
Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailhost);
Session session = Session.getDefaultInstance();

4.

Which of the statements about Message and MimeMessage class are true?
A.
B.
C.
D.
E.
(A)
(B)

5.

The javax.mail.Message class is used to create messages.
The javax.mail.Message class implements a Part interface.
The session object is created from message object.
The date and subject are parts of the message object.
The Part interface which specifies the attributes and content type of the message.
A, B, and C
C, D, and E

(C)
(D)

B, C, and D
B, D, and E

Can you arrange the steps to create a message object using the MimeMessage in sequence?
A.
B.
C.
D.
E.

A, B, C, D, E
E, D, C, A, B

(C)
(D)

B, C, D, E, A
D, C, B, E, A

Concepts

(A)
(B)

Set the content of the message
Set the attributes required
Create an empty message object from a session
Create a session object
Set the content type of the message

V 1.0 © Aptech Limited

Session
6.

10
JavaMail

You are trying to parse a comma delimited list of address to create an array of InternetAddress
class. Which of the following options will help you to achieve this?
A. String strCc = “mails.mike@gmail.com, fred@gmail.com, mike@gmail.
com ”;
try
{
InternetAddress[] ccddress = InternetAddress.parse(strCc,
false);
}
catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage();

B.

}
String strCc = “mails.mike@gmail.com, fred@gmail.com, mike@gmail.
com ”;
try
{
InternetAddress[] ccddress = ccddress.parse(strCc,
false);
}
catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage();

C.

}
String strCc = “mails.mike@gmail.com, fred@gmail.com, mike@gmail.
com ”;
try
{
InternetAddress[] ccddress = InternetAddress.parse(false,

Concepts

strCc);
}
catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage();
}

V 1.0 © Aptech Limited

Session

10
JavaMail

D. String strCc = “mails.mike@gmail.com, fred@gmail.com, mike@gmail.
com ”;
try {
InetAddress[] ccddress = InetAddress.parse(strCc,
false);
} catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage();
}

7.

Which of the statements about Store class are true?
A.
B.
C.
D.
E.

A
C

(C)
(D)

B
D

Concepts

(A)
(B)

The javax.mail.Store class represents a message store of the message.
The argument passed in the getStore() method can be POP3 or IMAP protocol.
To get a connection to the store you pass only user id as the authentication parameter.
To retrieve a message from email service, you have to gain access to the store first.
The Store class inherits the method getStore() from the super class Service

V 1.0 © Aptech Limited

Session

10
JavaMail

10.4.1 Answers
C
A
A
D
D
A
D

Concepts

1.
2.
3.
4.
5.
6.
7.

V 1.0 © Aptech Limited

Session

10
JavaMail

Summary
The JavaMail API is used to read, compose and send electronic messages. The JavaMail API is
not responsible for the actual transporting, delivering, and forwarding messages.

JavaMail session is created using the Administration Console. Session objects are defined with
specified properties in the MailConfiguration class.

In the context of a mailing system a session is a lasting connection between a user and a host,
usually a server. MimeMessage class object represents a MIME style email message.

Once the message object is created and its required attributes are set, the final step involves
sending the message to the recipient.

Creating and sending emails using JavaMail involves creating and sending a message, reading a
message and replying to a message. JavaMail does not implement an email server; it allows the
user to access an email server using Java API.

The JavaMail API does not require support for specific protocols; JavaMail includes support for
POP3, IMAP, and SMTP.

Concepts

V 1.0 © Aptech Limited