Вы находитесь на странице: 1из 473

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 pre-
paid 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
Scanning the user
Instructional
system and needs
Processes and
assessment
Material

2 6
Need Analysis
Assessment of
and design of
learning
curriculum

3 Design and
5
Strategies for
development of
delivery of
instructional
instructions
material 4
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
1
Session 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.

Feature Description
Swing GUI Components Contains all type of components, such as buttons
Concepts

to split panes to tables. Some components also


support features, such as sorting, printing, and
drag and drop.
Pluggable Look-and-Feel 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 Description
Accessibility API Allows User Interface (UI) to interact with different
products, such as screen readers and Braille
displays.
Java 2D API Supports high-quality 2D graphics, text, and images
to be developed in Java applications.
Internationalization 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 displays the AWT components added in a Java Applet.

Concepts

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


1
Session 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
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
Concepts

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


1
Session 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.

 Model
The Model represents all the data and the various states of the component. Data is provided by the
Concepts

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.

Figure 1.6: MVC Architecture

1.2.1 Swing Separable Model Architecture


Concepts

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 Model-
View-Controller architecture.

V 1.0 © Aptech Limited


1
Session 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
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


Concepts

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.

Method Description
setLookAndFeel(String className) 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
getSystemLookAndFeelClassName() systems Look and Feel if it exists or the name of
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
Concepts

the Java Look and Feel.


Table 1.2: Methods to set and get the Look and Feel

V 1.0 © Aptech Limited


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.

1.2.7 Dependencies of Look and Feel on Operating System


Swing provides three Look and Feel, Metal, and two Look and Feel which characterize the Look and Feel
Concepts

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


1
Session 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.
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.
Concepts

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 Examples Description


Top Level Containers JApplet, JDialog, One of these components
JFrame must be present in any swing
application. They form the root
of any container hierarchy.
General purpose Containers JPanel, JscrollPane, These are present in most swing
JTabbedPane, JToolBar applications.
Special Purpose containers J I n t e r n a l F r a m e , These play specific roles in the
JLayeredPane, JRootPane UI.
Table 1.3: Types of Containers
Concepts

V 1.0 © Aptech Limited


1
Session 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.
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.
Concepts

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 displays the content pane.

Concepts

Figure 1.11: Content Pane

V 1.0 © Aptech Limited


1
Session 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:

 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
Concepts

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();
Concepts

. . .
. . .
}
}

V 1.0 © Aptech Limited


1
Session 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 frmWindow = new
JFrame(“Login”);
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.
To display a JFrame, you first set the size and then use the setVisible() method in the following
manner:
Concepts

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 non-
responsive. 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.
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.
By default, the close operation of the JFrame is not functional. To provide the close functionality,
Concepts

you use the following method:


frmWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

V 1.0 © Aptech Limited


1
Session 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.
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.
Concepts

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 Constructs a JInternalFrame with a title, resizability, and
title, boolean resizable, closability.
boolean closeable)
JInternalFrame(String Constructs a JInternalFrame with a title, resizability,
title, boolean resizable, closability, and maximizability.
boolean closeable, boolean
maximizable)
JInternalFrame(String Constructs a JInternalFrame with the specified title,
title, boolean resizable, resizability, closability, maximizability, and iconifiability.
boolean closable, boolean
maximizable, boolean
iconifiable)

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


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.
Concepts

V 1.0 © Aptech Limited


1
Session 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 Description
init() 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.
Start() This method is invoked once after the init() method. It could be
used to start threads.
Paint() 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.
Stop() This method is invoked when the user leaves the page that contained
the applet. This method can be called more than once.
Destroy() 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.
Code Snippet 7:
Concepts

import javax.swing.JApplet;
...
public class MyApplet extends JApplet
{

V 1.0 © Aptech Limited


1
Session 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.
Figure 1.16 displays a JPanel.
Concepts

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.
Figure 1.17 displays the lightweight components.

Concepts

Figure 1.17: Lightweight Components

V 1.0 © Aptech Limited


1
Session 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.

Constructor Description
JLabel() Creates a label without text.
JLabel(String label) Creates a label with the specified text; where
label is a string.
JLabel(ImageIcon icon) Creates a label with the specified image; where
icon is an image.
JLabel(String label, ImageIcon icon) 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


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

...

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(); The getText() method can be used to retrieve
the text of the JLabel.
public void setText(String label); 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();

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”.

1.4.2 JButton
Concepts

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


1
Session Introduction to Swing

Constructor Description
JButton() 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);
...

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
Concepts

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() The getText() method is used to retrieve the
text of JButton.
Public void setText(string label) 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”);

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. Concepts

V 1.0 © Aptech Limited


1
Session 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
Figure 1.19 displays a JCheckBox.
Concepts

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.

Method Description
boolean isSelected() This retrieves the state of the JCheckBox. If
the check box is selected, it returns true else it
returns false.
Void setSelected(boolean state) This is used to set the state the JCheckBox. If
set to true then JCheckBox is selected.
Concepts

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


1
Session 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
Figure 1.20 displays JRadioButton.
Concepts

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.
Code Snippet 17:
Concepts

V 1.0 © Aptech Limited


1
Session 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 method retrieves the value of
JRadioButton.
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.
Table 1.14: JRadioButton Constructors

1.4.6 JTextField
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.
Concepts

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


1
Session Introduction to Swing

Table 1.15 lists the important methods of the JTextField.

Method Description
String getText() Returns the contents of the JTextField.
void setText(String text) Programmatically sets the text in the JTextField.
void setEditable(boolean editable) 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(): Creates a textarea without any text
public JTextArea(String text): Creates a textarea with the specified text; where
text is a string
public JTextArea(int rows, int Creates a textarea with the specified rows and the
columns) columns; where rows is an integer and a column is
an integer
Table 1.16: JTextArea Constructors
Figure 1.23 displays a JTextArea.
Concepts

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
Concepts

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


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.
By default, the asterisk character is echoed; it can be programmatically changed to any other character
desired.
Concepts

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.

Method Description
public string getText() Returns the contents of JPasswordField.
public void setText() Programmatically sets the text in
JPasswordField.
public void setEchoChar() Changes the default echo character to a specified
Concepts

character.
Table 1.17: Methods of JPasswordField

V 1.0 © Aptech Limited


1
Session 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
event.

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


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 Source Listeners Interface Methods


ActionEvent B u t t o n , ActionListener void actionPerformed(ActionEven
Menu, List t ae)
AdjustmentEvent Scrollbar AdjustmentListener void adjustmentValueChanged(Adj
ustmentEvent ae)
ItemEvent Check box, ItemListener void itemStateChanged(ItemEvent
List ie)
Concepts

V 1.0 © Aptech Limited


1
Session Introduction to Swing

Events Source Listeners Interface Methods


MouseEvent Mouse MouseListener 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)
WindowEvent Window WindowListener void windowActivated(WindowE
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


Since JButton is a Swing component, the Event-Delegation Model is used to handle its events.
Concepts

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:
public void itemStateChanged(ItemEvente)
The method itemStateChanged() contains the action code to be executed when a JCheckBox
Concepts

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


1
Session 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


A JRadioButton component listens using either java.awt.event.ActionListener or java.
awt.Event.ItemListenerinterface.
Concepts

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);
rabbitButton.setActionCommand(rabbitString);

Concepts

V 1.0 © Aptech Limited


1
Session 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”));
}
});

Figure 1.27 shows the output for Code Snippet 26.


Concepts

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


1
Session 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.
Code Snippet 29:
Concepts

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
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.
addKeyListener method is used to register the class with the component. When the keyboard event
Concepts

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


1
Session 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() This method returns the character for the key event.
int getKeyCode() This method retrieves the Unicode value of the character
for the key event.
public int This method retrieves the location of the key that fired
getKeyLocation() the key event.
public getKeyText(int Returns a String describing the keyCode, such as ‘HOME’,
keyCode) ‘F1’ or ‘A’.
public boolean This returns true if the key firing the event was an action
isActionKey() key such as cut, copy, paste, and so on.
void setKeyChar(char Set the keyChar value to indicate a logical character.
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));
addKeyListener(this);
}
Concepts

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.
public interface FocusListener extends EventListener
The class interested in processing a focus event would implement this interface and the mentioned
Concepts

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


1
Session 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
keyboard focus.
void focusLost(FocusEvent e) 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


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

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 shows the output for Code Snippet 31.

Concepts

Figure 1.28: Output for Code Snippet 31

V 1.0 © Aptech Limited


1
Session 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
...
}
public void mouseClicked(MouseEvent e) {
// This method is invoked as a result of
Concepts

// 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 create a swing project using NetBeans IDE, perform the following steps:

 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.
Concepts

 In the Create Main Class box, delete default content.

 Select Set as Main Project check box.

 Click Finish.

V 1.0 © Aptech Limited


1
Session 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
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.
Concepts

 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


Next, we need to compile the program:

 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
Concepts

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


1
Session 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)
Examples of JComponent Methods are as follows:

 void setMinimumSize(Dimension dim)

 void setPreferredSize(Dimension dim)

 void setMaximumSize(Dimension dim)

 void setBorder(Border b)
Concepts

 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
Concepts

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


1
Session 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.

Figure 1.30: setMnemonic()


Concepts

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”.
Code Snippet 35:

btnSave.setToolTipText(“Save”);
Concepts

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

V 1.0 © Aptech Limited


1
Session 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.

Figure 1.32: setBackground()

1.7.6 setForeground()
Concepts

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.
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.
To set a border to a component, you use the setBorder() method and the BorderFactory class:
Concepts

 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


1
Session 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:

JPanel pnlPanel; pnlPanel = new JPanel();


Border raisedbevel, loweredbevel;
Concepts

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.

Figure 1.35: setEnabled()


Concepts

V 1.0 © Aptech Limited


1
Session 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 Introduction to Swing

1.7.10 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);

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 top-
level container such as JFrame, no components should be added to the content pane after the
setVisible(true) method has been invoked.
When the setVisible(true) method is invoked on a top-level container such as JFrame, it puts
Concepts

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


1
Session 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:

 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
Concepts

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 event-
dispatch thread. The invokeLater() method returns immediately regardless of when the run()
method is invoked.
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.
Using the SwingUtilities.invokeLater() method ensures that the imminent clash between the
main-thread and the event-dispatch thread is averted.
Concepts

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


1
Session Introduction to Swing

1.9 Check Your Progress


1. Which of the statements about JFC and Swing are true?

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

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


(B) C, D, and E (D) B, C, and D
2. Can you match the descriptions against the corresponding features of AWT and Swing?

Features Description
A. AWT 1. Swing
B. Peer components 2. Platform dependent
C. Swing components 3. Abstract Window Toolkit
D. Lightweight components 4. GUI based application
E. Heavyweight components 5. Platform independent

(A) A-4, B-2, C-5, D-1, E-3 (C) A-2, B-4, C-5, D-1, E-3
(B) A-4, B-2, C-5, D-3, E-1 (D) A-5, B-2, C-4, D-3, E-1
3. Which of these statements about MVC and Separable Model Architecture are true?

A. MVC Architecture was first introduced in Smalltalk.


B. Model represents the view of the Component.
C. Controller reacts to user inputs from Keyboard and Mouse.
D. View represents the data.
E. Separable Architecture combines the View and Controller.

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


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

4. Which statements about container are true?

A. Glass pane is hidden by default.


B. Layered pane can hold components in specified Z-order.
C. The menu bar can be added to the content pane.

V 1.0 © Aptech Limited


1
Session Introduction to Swing

D. The general purpose container cannot be added to a top level container.


E. The object reference of a content pane is retrieved using the getContentPane()
method.

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


(B) B, C, and E (D) B, C, D, and E
5. Which of the statements about JFrame, JApplet, and JPanel are true?

A. The JPanel is a container and not a component.


B. The setSize() method brings JFrame into realized state.
C. By default, close operation of JFrame is not functional.
D. Applet makes Web pages more dynamic.
E. The stop() method of JApplet is invoked only once in life time of JApplet.

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


(B) A, D, and E (D) B, C, and D
6. Which of the following statements about JTextField, JTextArea, and JPasswordField are
true?

A. JPasswordField can be created with the constructor public


JPasswordField(“Pass word”);
B. JTextField allows to input single line of text.
C. The method setEditable(false) allows you to edit the text.
D. JTextArea does not allow you to edit the text.
E. The text in the JTextArea can be set programmatically.

(A) B and E (C) A and C


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

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


B. JButton btnOk = new JButton(new ImageIcon(“Ok.gif”), “Ok”);
C. JButton btnOk = new JButton(“Ok”, new ImageIcon(“Ok.gif”));
D. JButton btnOk = new JButon(new ImageIcon(“Ok.gif”));
Concepts

8. 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


1
Session Introduction to Swing

A. btnCancel. setMemmonic (‘C’);


btnCancel.setToolTiptext(“Cancel operation”);
B. btnCancel.setMnemonic(‘O’);
btnCancel.setToolTipText(“Cancel operation”);
C. btnCancel.setMnemonic(‘C’);
btnCancel.setToolTipText(Cancel operation);
D. btnCancel.setMnemonic(KeyEvent.VK_O);
btnCancel.setToolTipText(“Cancel operation”);
Concepts

V 1.0 © Aptech Limited


1
Session Introduction to Swing

1.9.1 Answers
1. D
2. A
3. D
4. A
5. A
6. A
7. C
8. D

Concepts

V 1.0 © Aptech Limited


1
Session 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.

Figure 2.1: JScrollPane


As shown in figure 2.1, a JScrollPane provides both horizontal and vertical scrolling. The JScrollPane
Concepts

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


2
Session 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.

Figure 2.2: Corners and Headers of a JScrollPane


The JScrollPane has a JViewport which manages the visible area of the client. The viewport
Concepts

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 shows the three areas of a scroll bar.

Concepts

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


2
Session 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
frmDisplay.getContentPane().add(scpScrollPane);
Concepts

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);
// Add the components of the client
...
Concepts

// Construct the scroll pane with the old view


scpScroller = new JScrollPane(pnlClient);
...

V 1.0 © Aptech Limited


2
Session 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 Description
public void This method is used to set a component at the corner of a scroll
setCorner(String key, pane.
Component corner)
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.
The argument Corner is the component to be added at the
corner.
public void setHorizon This method determines when the horizontal scrollbar appears in
talScrollBarPolicy(int the scroll pane.
policy)
The argument policy can have one of the following values
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_
NEEDED
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
Example:
JScrollPane scpScrollPane = new JScrollPane();
scpScrollPane.setHorizontalScrollBarPolicy(Scroll
Concepts

PaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Method Description
public void setVertic This method determines when the vertical scrollbar appears in the
alScrollBarPolicy(int JScrollPane.
policy)
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 This is used to add a vertically long component as the row header.
View(Component view) 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);
// Creates a label with icon
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
Concepts

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


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);
}
...

Figure 2.7 shows the output for Code Snippet 3.


Concepts

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.

Constructor Description Example


JSlider() Creates a horizontal slider bar with the /* Creates a slider
bar with the default
Concepts

range 0 to 100 and an initial value of


50. properties */
JSlider sdrRed = new
JSlider();

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Constructor Description Example


JSlider(int Creates a slider bar using the specified /* Creates a slider
orient) orientation with the range 0 to 100 and bar with the default
an initial value of 50. properties and
vertical orientation */
The argument orientation can
have one of the following values: JSlider sdrSlider = new
SwingConstants.HORIZONTAL and JSlider(SwingConstants.
SwingConstants.VERTICAL VERTICAL);
JSlider(int Creates a horizontal slider bar using /* Creates a slider bar
min, int max) the specified minimum and maximum with the minimum value 10
values with an initial value of 50. and maximum value 50 */
JSlider sdrSlider = new
The argument min and max are the
JSlider(10,50);
minimum and maximum integer values
to be set.
JSlider(int Creates a horizontal slider bar using /* Creates a slider bar
min, int max, the specified minimum, maximum, and with the minimum value
int value) initial value. 10, maximum value 50 and
initial value 0 */
JSlider sdrSlider = new
JSlider(0,255,0);
JSlider(int Creates a slider bar with the specified /* Creates a slider bar
orient, int orientation and the specified minimum, with the orientation
min, int max, maximum, and initial values. vertical, minimumvalue
int value) 10, maximum value 255,and
The argument orient is initial value 0 */
one of the following values:
JSlider sdrRed = new
SwingConstants.HORIZONTAL and JSlider(SwingConstants.
SwingConstants.VERTICAL. VERTICAL,0,255,0);

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.

Constructor Description Example


public int getValue() Returns the current /* Retrieve the value of the
Concepts

position of the slider in the slider in the slider bar */


slider bar as an integer. int sliderValue = sdrRed.
getValue();

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Constructor Description Example


Public void Sets the position of the int sliderValue = 25;
setValue(intvalue) slider in the slider bar . . .
programmatically. The
value set in the parameter sdrRed.
setValue(slidervalue);
should be within the range
of minimum and maximum /* Sets the value of the
value of the slider bar. slider in the slider bar */

The argument value is an int sliderValue = 25;


integer which specifies the sdrRed.
position of the slider to be setValue(slidervalue);
set.
public void Sets the orientation of the /* Sets the orientation of
setOrientation(int slider bar to horizontal or the slider bar horizontal */
orientation) vertical. sdrRed.setOrientation(SwingC
onstants.HORIZONTAL);
public void Is used to set the major tick /* Sets the major tick
setMajorTickSpacing(int spacing. spacing to 10 for a slider
spacing) bar with the range 0 to 50
The argument spacing is */
the integer value to be set
sdrSlider.
as major tick spacing.
setMajorTickSpacing(10);
public void Is used to set the minor tick /* Sets the minor tick
setMinorTickSpacing(int spacing. spacing to 5 for a slider
spacing) bar with the range 0 to 50
The argument spacing is */
the integer value to be set
sdrSlider.
as minor tick spacing.
setMinorTickSpacing(5);
public void This displays the ticks on /* Displays the ticks on the
setPaintTicks(boolean the slider bar if argument is slider bar */
set) set to true. sdrSlider.
setPaintTicks(true);

public void Determines that the track /* Paints the track of the
setPaintTrack(boolean of the slider bar should be slider bar */
Concepts

set) painted, if the argument


passed is true.
sdrSlider.
setPaintTrack(true);

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Constructor Description Example


public void Snaps the slider to the /* Snaps the slider to the
setSnapToTicks(boolean nearest tick mark wherever nearest tick mark in the
set) the user positions the slider bar */
slider, If true, the slider is
snapped to the nearest
sdrSlider.setSnapToTicks();
tick mark where the user
positions the slider. If false
is passed as an argument
the slider moves freely
across the slider bar.
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.
public void This determines if the /* Paints the labels of
setPaintLabels(boolean major tick’s labels are to be major ticks on the slider
set) painted. If the argument is bar */
set to true then the labels
are painted.
sdrSlider.
The argument set, If set setPaintLabels(true);
to true, the major tick
labels are displayed. If set
to false, the labels are not
displayed.
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.
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.
Concepts

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();
}
...

Figure 2.9 shows the output for the Code Snippet 4.


Concepts

Figure 2.9: Output - Event Handling on JSlider

V 1.0 © Aptech Limited


2
Session 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
tmrAlert = new Timer(5000, new ActionListener()
{
Concepts

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 displays the progress bar.

Figure 2.10: Progress Bar


Concepts

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


2
Session 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 Description Example


JProgressBar() Creates a horizontal progress JProgressBar pgbLongTask
bar with default properties. By = new JProgressBar();
default min is zero and max is
100.
JProgressBar(int Creates a progress bar with JProgressBar pgbLongTask
orient) specifies orientation. By default, = new JProgressBar(JProgr
min is 0 and max is 100. essBar.VERTICAL);

The argument orient is the


integer with one of the following
valid values:
JProgressBar.HORIZONTAL,
JProgressBar.VERTICAL.
JProgressBar(int Creates a horizontal progress bar JProgressBar
min, int max) by default, with the specified pgbLongTask =
minimum and maximum values.
new JProgressBar
(0,100);
JProgressBar(int Creates a progress bar with the JProgressBar pgbLongTask=
orient, int min, specified orientation, minimum, new JProgressBar(JProgres
int max) and maximum values. sBar.VERTICAL,0,100);

Table 2.4: Constructor Methods of JProgressBar


Concepts

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 shows the output for Code Snippet 7.

Concepts

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


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.

Method Description Example


void setMinimum(int n) Is used to set the minimum value /* Sets minimum value
of the progress bar. of the progress bar to
10 */
The argument n is the minimum
integer value to be set.
pgbLongTask.
setMinimum(10);
void setMaximum(int n) Is used to set the maximum /* Sets maximum value
value of the progress bar. of the progress bar to
50 */
pgbLongTask.
setMaximum(50);
void setValue(int n) Is used to set progress value of /* Sets the value of
the progress bar. the progress bar to 0
*/
scpLongTask.
setValue(0);
void setString(String Is used to set the string /* Displays the message
s) representation of the numeric indicating that half of
value of the progress bar. This the task is completed
*/
value is followed by a percentage
sign. scpLongTask.
setString(“Half way
reached”);
void setStringPainted Determines whether the string scpLongTask.
representation of the numeric setStringPainted(true);
(boolean b)
value is to be displayed or not. If
the argument is set to true then
the value is displayed.
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
Concepts

displayed.

Table 2.5: Methods of JProgressBar

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Table 2.6 lists other methods of JProgressBar.

Method Description
Void setIndeterminate(boolean) Setting Boolean value to ‘True’ will make
indeterminate progress bar. Setting Boolean value to
‘False’ will make it determinate, which is default.
Void setOrientation(int) Sets a progress bar horizontal or
vertical by specifying JProgressBar.
HORIZONTALorJProgressBar.VERTICAL.
Int getOrientation() Gets a horizontal/ vertical progress bar.
String getString() Gets percentage string.
Public int getValue() Returns current value from BoundedRangeModel.
public int getMinimum() Returns current minimum value from
BoundedRangeModel.
public int getMaximum() Returns current maximum value from
BoundedRangeModel.
Protected ChangeListener Used to implement custom ChangeListener.
createChangeListener()
public void addChangeListener(Chan Adds specified ChangeListener to progress bar
geListener cl)
public void removeChangeListener(C Removes ChangeListener from progress bar.
hangeListener cl)
public BoundedRangeModelgetModel() Returns model used by the progress bar.
public void setModel(BoundedRangeM Replaces current model used by progress bar.
odel newModel)
Protected void Fires events of type ChangeEvent to its registered
fireStateChanged() listeners. Only subclasses of JProgressBar can
invoke it.
Table 2.6: Other Methods of JProgressBar

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.
Concepts

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
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.
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.
Concepts

V 1.0 © Aptech Limited


2
Session 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;


// Instantiate a number format object
numberFormat = NumberFormat.getNumberInstance();
Concepts

// 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


frmDetails.getContentPane().add(txfDate);

2.6.4 Using JFormattedTextField with Customized Formatter


Concepts

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


2
Session Basic Swing Components

Table 2.7 lists the mask characters.

Mask Character Description


# Any valid number.
‘ Escape character for escape sequence
U Any character, converted to uppercase.
L Any character, converted to lowercase.
A Any character or number.
? Any single character.
* One or more characters.
H 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
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.
Concepts

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 Description Example


JEditorPane() Creates a JEditorPane with no JEditorPane epnEditor;
text initialized. epnEditor = new
JEditorPane();
JEditorPane(String Creates a JEditorPane with the JEditorPane epnEditor;
url) throws contents specified by url. epnEditor = new
IOException
The argument url is the string JEditorPane(“http://java.
sun.com/
specifying the path of the page or
document to be displayed. index.html”);
JEditorPane(URL Creates a JEditorPane with the JEditorPane epnEditor;
url) throws contents from the specified url. // Creates an object of
IOException
the URL
URL url = new URL
(“http://java.sun.com/
index.html”);

// Creates a JEditorPane
// with the specified URL
epnEditor = new
JEditorPane(url);
JEditorPane(String Creates a JEditorPane with the // Creates an object of
type, String text) specified Multi Purpose Internet the URL
Mailing Extension (MIME) type, and URL url = new URL(
the initial text.
“http://java.sun.com/
The argument type is a MIME type. index.html
It could take one of the following
”);
values:
text/plain
/* Creates a JEditorPane
text/rtf with
text: Is the initial text to be the specified URL and MIME
displayed in the JEditorPane. */
Concepts

epnEditor = new
JEditorPane
(url, ”text/html”);

Table 2.8: Constructor Methods of JEditorPane

V 1.0 © Aptech Limited


2
Session 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 Description Example


public void Is used to set the text in the String info;
setText(String JEditorPane. . . .
text)
The argument text is the textual info = “Once upon a
contents to be displayed in time,……”;
JEditorPane.

// Sets the text in the


editor pane
epnEditor.setText(info);
Concepts

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Method Description Example


public void Is used to display the contents of try
setPage(URL url) the page referenced by the url. {
throws IOException
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
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.
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
Concepts

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


2
Session 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.
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
Concepts

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.getEventType()== HyperlinkEvent.EventType.Activated)getPages(e.
getURL().toString());
if (e instanceof HTMLFrameHyperlinkEvent) {HTMLFrameHyperlinkEvent evt
Concepts

= (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)contents.


getDocument();doc.processHTMLFrameHyperlinkEvent(evt);
} else {
try {

V 1.0 © Aptech Limited


2
Session 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
ReadURLFileNew();
Concepts

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.
Table 2.10 shows constructors of JTextPane.
Concepts

Constructor Description Example


JTextPane() Creates a JTextPane with the JTextPane txpText;
document set to null. txpText = new
JTextPane();

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Constructor Description Example


JTextPane(StyledDocument Creates a JTextPane with a JTextPane txpText;
doc) specified document. StyledDocument doc = new
The argument doc is an object DefaultStyledDocument();
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:

 Retrievethe StyledDocument of a JTextPane is retrieved using the method


getStyledDocument().

 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.
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);
// Then add a ‘regular’ style with the font ‘SansSerif’
Style regular = doc.addStyle(“regular”, def);StyleConstants.
Concepts

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);
//Disables the editing of the JTextPane
txpPane.setEditable(false);
Concepts

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


2
Session 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.

Constructor Description
ImageIcon() Creates an image.
ImageIcon(Byte[] image data) Creates an icon from an array of bytes
read from a JPEG or GIF.
ImageIcon(Image image) Creates an image icon from an image
object.
ImageIcon(Image image, String Creates an image icon with the image
description) and a description.
ImageIcon(string filename) Creates an image icon from a specified
file.
ImageIcon(URL location) 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)

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

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.
Code Snippet 19:

Concepts

V 1.0 © Aptech Limited


2
Session 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
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.
Concepts

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) Sets the border of the Swing component.
BordercreateLineBorder(colo Creates a line border and specifies the color of the line.
r)
createLineBorder(color, int) Creates a line border with specified color and width.
BordercreateEtchedBorder() Creates an etched border.
BordercreateemptyBorder() Creates an invisible border.
BordercreateemptyBorder(int, Creates an invisible border. The arguments specify the
int, int, int) number of pixels that the border occupies at the four
corners.
public static TitledBorder Creates a new titled border with the specified title, the
createTitledBorder(String default border type, the default text position, the default
title) 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);
lowbev = BorderFactory.createLoweredBevelBorder();
emp = BorderFactory.createEmptyBorder();
Concepts

jCompa.setBorder(blkln);
jCompb.setBorder(retched);
jcompc.setBorder(lowbev);
jCompd.setBorder(emp);

V 1.0 © Aptech Limited


2
Session 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.
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


Concepts

 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”
+ “pressing one of the following buttons.\n”
+ “Do you understand?”,JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_
OPTION);
Concepts

V 1.0 © Aptech Limited


2
Session 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);
}
}
});

Figure 2.15 shows the output for Code Snippet 22.


Concepts

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 warning”, JOptionPane.WARNING_MESSAGE);
creates a message dialog box.

 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:
public static int showConirmDialog(Component parentComponent, Object
message)
Where,
Concepts

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


2
Session 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, Object message, String title, int
messageType,
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, WARNING_MESSAGE, QUESTION_MESSAGE,
or PLAIN_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”, “Unix”, “Linux”};String s=
(String)JOptionPane.showInputDialog(
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
Concepts

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, WARNING_MESSAGE, QUESTION_MESSAGE,
or PLAIN_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.QUES-
TION_MESSAGE, null, options, options[0]);
This displays the option dialog box to connect, disconnect, or quit.
Figure 2.16 shows the types of JOptionPane dialog box.
Concepts

V 1.0 © Aptech Limited


2
Session Basic Swing Components

Figure 2.16: Input and Option Dialog Box


Figure 2.17 shows types of JOptionPane dialog box.
Concepts

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.
title: Is the title to be given to the dialog box.
JDialog(Frameparent, Creates a modal dialog box with the title specified if modal is
Stringtitle,booleanm true.
odal)
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


Figure 2.18 shows a customized JDialogBox.
Concepts

V 1.0 © Aptech Limited


2
Session 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
...
}}

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
Concepts

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.

Figure 2.19: Output for Code Snippet 24

Concepts

V 1.0 © Aptech Limited


2
Session 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 = new


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

B. JScrollPane scpScrollPane;JTextArea txtNotes;txtNotes = new


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

C. JScrollPane scpScrollPane;JTextArea txtNotes;txtNotes = new


JTextArea(); scpScrollPane = new JScrollPane(txaNotes);
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 Basic Swing Components

B. 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


2
Session 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();
txfNumber = new JFormattedTextField(numberFormat);
B. NumberFormat numberFormat;JFormattedTextField txfNumber;
numberFormat = NumberFormat.getNumberInstance(numberFormat);
txfNumber = new JFormattedTextField();
C. NumberFormat numberFormat;JFormattedTextField txfNumber;
numberFormat = numberFormat.getNumberInstance();
txfNumber = new JFormattedTextField(numberFormat);
D. NumberFormat numberFormat;JFormattedTextField txfNumber;
txfNumber = NumberFormat.getNumberInstance();
txfNumber = new JFormattedTextField();
Concepts

V 1.0 © Aptech Limited


2
Session Basic Swing Components

4. 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);
txpPane.setEditable(true);
B. JFrame frmDisplay;JScrollPane scpScroller;
...
JTextPane txpPane;
scpScroller = new JScrollPane(txpPane);frmDisplay.
getContentPane().add(scpScroller);
txpPane.setEditable(false);
C. JFrame frmDisplay;JScrollPane scpScroller;
...
JTextPane txpPane;
scpScroller = new JScrollPane(JTextPane);txpPane.
add(scpScroller);txpPane.setEditable(false);
D. 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?

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


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

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

V 1.0 © Aptech Limited


2
Session Basic Swing Components

6. 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 Basic Swing Components

C. 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


2
Session Basic Swing Components

2.9.1 Answers
1. C
2. A
3. A
4. D
5. D
6. A
Concepts

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
3
Session 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.

3.1.2 Steps for Using Layer Manager


Concepts

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 Description Example


void setPreferredSize(Di This is used to set the preferred size // Sets preferred
mension preferredSize) of a component when it is added to size of the button
the container. labeled OK
btnOk.
Syntax:
setPreferredSize(new
void setPreferredSize(Dime Dimension(20,20));
nsion preferredSize)
where,
preferredSize: is an object
of Dimension class used to
encapsulate the preferred width
and height of a component in a
single object.
void This is used to set the minimum // Sets the minimum
setMinimumSize(Dimension size of a given component. size of the button
minimumSize) labeled OK
Syntax:
btnOk.
void setMinimumSize(new
setMinimumSize(Dimension Dimension(20,20));
minimumSize)
where,
minimumSize: is an object
of Dimension class used to
encapsulate the minimum width
and height of a component in a
single object.
Concepts

V 1.0 © Aptech Limited


3
Session Layout Managers

Method Description Example


void This is used to set the maximum // Sets maximum
setMaximumSize(Dimension size of a given component. size of the button
maximumSize) labeled OK
Syntax:
btnOk.
void setMaximumSize(new
setMaximumSize(Dimension Dimension(20,20));
maximumSize)
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.

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.
Concepts

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.
BorderLayout Allows positioning of components in five locations. East,
West, North, South, and Center.
GridLayout Arranges the components in terms of rows and columns.
CardLayout Arranges components like a deck of cards.
Table 3.2: Layout Managers
Figure 3.2 displays the layout managers.

Figure 3.2: Types of Layout Managers

3.2 FlowLayout Manager


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
Concepts

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


3
Session 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 Example


FlowLayout() This adds the components with a centered // Creates the flow
alignment and a gap of five pixels both layout manager
horizontally and vertically. FlowLayout layout;
layout = new
FlowLayout();
FlowLayout Adds components with a specified alignment. // Creates the flow
(int) layout // manager with
Syntax: left alignment
FlowLayout (int alignment) FlowLayout layout;
where, layout = new
FlowLayout(FlowLayout.
alignment: is one of the following valid LEFT);
values:
FlowLayout.CENTER, FlowLayout.LEFT, or
FlowLayout.RIGHT
FlowLayout Adds the components with specified alignment, /* Creates the low
(int, int, horizontal gap, and vertical gap. layout manager with
int) left alignment,
Syntax: horizontal gap of 10
pixels and vertical gap
FlowLayout(int alignment, int
of 15 pixels */
horizontal-gap, int vertical-gap)
FlowLayout layout;
where,
layout = new
horizontal_gap: is an integer variable
Concepts

FlowLayout(FlowLayout.
representing horizontal gap between LEFT,10,15);
components.
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);
// Creates a textield.
txtName = new JTextField();
Concepts

// Adds the textield to the frame


getContentPane().add(txtName);
}
}

V 1.0 © Aptech Limited


3
Session 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.

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.
Concepts

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 as its default layout
manager.

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


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

Constructor Description Example


Concepts

BorderLayout() Create the border layout with no gaps // Creates the border
between components. layout manager
BorderLayout layout;
layout = new
BorderLayout();

V 1.0 © Aptech Limited


3
Session Layout Managers

Constructor Description Example


BorderLayout(int Create the border layout with the /* Creates the border
horizontal gap, specified horizontal and vertical gap. layout manager with
int vertical horizontal gap of 10
gap) Syntax: pixels and vertical gap
of 15 pixels */
BorderLayout(int horizontal-
gap, int vertical-gap) BorderLayout layout;
where, layout = new
BorderLayout(10,15);
horizontal_gap: is an integer
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 re-
turned.
Syntax:
Component add (Component comp, int index)
where,
comp: Is the GUI component to be added.
index: Is the direction where the component is to be placed. Valid value includes:
BorderLayout.EAST, BorderLayout.WEST, BorderLayout.NORTH, Border-
Concepts

Layout.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


The advantages of using BorderLayout manager are as follows:
Concepts

 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


3
Session 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 Description Example


GridLayout(int, Creates a GridLayout manager with specified /* Creates the grid
int) number of rows and columns. The gap layout manager with 5
between the grid of components created is rows and 5 columns */
zero. GridLayout layout = new
GridLayout(5,5);
Syntax:
GridLayout(int rows, int columns)
Concepts

where,
rows: Is an integer specifying number of rows
columns: Is an integer specifying number of
the columns.

V 1.0 © Aptech Limited


3
Session Layout Managers

Constructor Description Example


GridLayout(int, Creates a GridLayout with specified number /* Create the grid
int, int, int) of columns and rows and with specified layout manager with
horizontal and vertical gaps between 5 rows, 5 columns,
horizontal gap of 10
components.
pixels and vertical gap
Syntax: of 15 pixels */

GridLayout(int rows, int columns, int GridLayout layout = new


horizontal_gap, int vertical_gap) GridLayout(5,5,10,15);

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.

Figure 3.9: Arrangement of Components - GridLayout

3.4.2 Benefits and Drawbacks


Concepts

The advantages of GridLayout manager are as follows:

 Simple to use.

 Useful for grouping components in a rectangular pattern.

V 1.0 © Aptech Limited


3
Session 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 Description Example


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

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();

Figure 3.11 shows the output of Code Snippet 3.

Concepts

Figure 3.11: Output – Panel

V 1.0 © Aptech Limited


3
Session 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 Description Example


void first(Container Makes the first card of the // Creates the card
parent) container visible, where parent layout manager
is the container governed by CardLayout cl = new
CardLayout();
the CardLayout manager.
. . .
// Make the first
card visible
cl.first(pnlCards);
void next(Container Makes the next card of the // Creates the card
parent) container visible. layout manager
CardLayout cl = new
CardLayout();
. . .
// Makes the next
card visible
cl.next(pnlCards);
void Makes the previous card of the // Creates the card
previous(Container container visible. layout manager
parent)
CardLayout cl = new
CardLayout();
. . .
// Makes the previous
// card visible
cl.previous(pnlCards);
void last(Container Makes the last card of the // Creates the card
parent) container visible. layout manager
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).

3.6.1 GridBagLayout Manager


Concepts

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


3
Session 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 Description
gridx and gridy These constraints specify the row and column. The leftmost column has
gridx = 0, the top row has gridy = 0.
gridwidth and gridwidth specifies how many columns the component will span and
gridheight gridheight specifies how many rows the component will span.
fill 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.
ipadx and ipady 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.
Insets 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.
anchor 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.
weightx and The constraint weightx decides how to distribute space among columns.
weighty 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.
Code Snippet 4:

Container c;
Concepts

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);
gbc.gridx = 0;
Concepts

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

V 1.0 © Aptech Limited


3
Session 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.
Code Snippet 5 demonstrates how to add components using absolute positioning.
Code Snippet 5:
Concepts

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[])
Concepts

{
JPanel container = new JPanel();

V 1.0 © Aptech Limited


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.
comp1: the current component.
distance: the fixed distance between components/container.
Concepts

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.
Code Snippet 7:

Concepts

V 1.0 © Aptech Limited


3
Session 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
= new JButton (“Button5”);
add (btn1); add (btn2); add (btn3); add (btn4); add (btn5);
Concepts

// 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, btn2, 5, SpringLayout.EAST,
btn1);
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


3
Session 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
composition.
Concepts

 Sequential Arrangement
In a sequential group the components are placed one after another, similar to BoxLayout or Flow-
Layout 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()
where,
double: Is the height of this instance returned by the method in double precision.
Concepts

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


3
Session 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 Description
void addLayoutComponent This method adds the component to the layout and
(String name, Component associate them with the string.
comp)
void removeLayoutCompon This method is called by the Container methods remove
ent(Component) and removeAll.
Dimension preferredLayo This is called by the Container class’s
utSize(Container) getPreferredSize() method.
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.
Concepts

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;
}
/* Required by LayoutManager. */
public void addLayoutComponent(String name, Component comp) {
Concepts

}
/* Required by LayoutManager. */
public void removeLayoutComponent(Component comp) {
}

V 1.0 © Aptech Limited


3
Session 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;
}
/* Required by LayoutManager. */
/*
Concepts

* This is called when the panel is first displayed,


* and every time its size changes.

V 1.0 © Aptech Limited


3
Session 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;
}
if (maxWidth != preferredWidth) {
xFudge = (maxWidth - preferredWidth)/(nComps - 1);
Concepts

}
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.
// Another choice would be to do what we do to x.
}
Concepts

// Set the component’s size and position.


c.setBounds(x, y, d.width, d.height);

V 1.0 © Aptech Limited


3
Session 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


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


Concepts

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);

3.9.2 LayerUI Class


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
Concepts

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


3
Session Layout Managers

Table 3.10 shows the most commonly overridden methods.

Method Description
paint(Graphics g, JComponent c) This method draws the target component.
super.paint(g, c) This method renders the target component the
same way as swing.
installUI(JComponent c) This method is called to initialize a component
associated with the LayerUI subclass.
uninstallUI(JComponent c) 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.
Code Snippet 13:
Concepts

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.
Shaped windows: Create windows with a certain shape such as circle, oval, and so on.

 To Implement Uniform Translucency


Concepts

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


3
Session 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);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Concepts

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();
}
}
});
}
}

Figure 3.16 shows a window with 55% opaqueness.

Concepts

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;

Paint p =
new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
Concepts

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”);
System.exit(0);
Concepts

V 1.0 © Aptech Limited


3
Session 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(
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK
Concepts

);

V 1.0 © Aptech Limited


3
Session Layout Managers

3.9 Check Your Progress


1. Which of these statements about the Layout Managers are true?

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

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


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

2. Which of these statements about FlowLayout manager are true?

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

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


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

3. 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; setLayout(new FlowLayout()); lblName = new


JLabel(“Name”);
Concepts

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

V 1.0 © Aptech Limited


3
Session Layout Managers

C. JLabel lblName; setLayout(new FlowLayout());


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

4. Which of the statements about BorderLayout manager are true?

A. A BorderLayout manager allows to add only 6 components.


B. By default the component is added to the center if the direction is not specified.
C. You cannot specify the direction where the component is to be placed.
D. The center component stretches both horizontally and vertically.
E. JFrame and JDialog have the BorderLayout Manager.

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


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

5. 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”);
pnlPanel.add(lblStatus,NORTH);
B. JPanel pnlPanel; JLabel lblStatus;
pnlPanel = new JPanel(); pnlPanel.setLayout(new BorderLayout());
lblStatus = new JLabel(“Status”);
add(lblStatus,BorderLayout.NORTH);
C. JPanel pnlPanel; JLabel lblStatus;
pnlPanel = new JPanel(); pnlPanel.setLayout(new BorderLayout());
lblStatus = new JLabel(“Status”);
Concepts

pnlPanel.add(lblStatus, BorderLayout.NORTH);
D. 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 Layout Managers

6. Which of the statements about GridLayout manager are true?

A. The GridLayout manager makes all components of same size.


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

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


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

7. 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);
. . .
. . .
btnZero = new JButton(“0”); pnlNumericPad.add(btnZero);
B. 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);
. . .
. . .
Concepts

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

V 1.0 © Aptech Limited


3
Session 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);
. . .
. . .
btnZero = new JButton(“0”); pnlNumericPad.add(btnZero);
D. 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);
. . .
. . .
btnZero = new JButton(“0”); add(btnZero);
Concepts

V 1.0 © Aptech Limited


3
Session Layout Managers

3.9.1 Answers
1. C
2. C
3. B
4. C
5. C
6. A
7. A

Concepts

V 1.0 © Aptech Limited


3
Session 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 displays the menu system.

Concepts

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


4
Session 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();
...
// Adds the JMenuBar to the top level container JFrame
Concepts

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
mnuFile = new JMenu(“File”);
mnuEdit = new JMenu(“Edit”);
Concepts

// Adds the menu to the menu bar


mbrMenubar.add(mnuFile);
mbrMenubar.add(mnuEdit);

V 1.0 © Aptech Limited


4
Session 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);
Figure 4.4 displays the mnemonic and separator in the JMenu.
Concepts

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;
mniOpen = new JMenuItem(“Open”, new ImageIcon(“Open.gif”));
Concepts

V 1.0 © Aptech Limited


4
Session 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)


The method is used to set the mnemonic character.
Concepts

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);

Figure 4.6 displays features of the JMenuItem.

Concepts

Figure 4.6: Features of JMenuItem

V 1.0 © Aptech Limited


4
Session 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.
Figure 4.7 displays sub-menu.
Concepts

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


A menu item component listens using the java.awt.event.ActionListener interface. This interface
has one method:
 void actionPerformed(ActionEvent e)
Concepts

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


4
Session 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.
Figure 4.9 displays the JCheckBoxMenuItem.
Concepts

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
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);
// Adds the check box menu item to the ‘Toolbars’ menu item
Concepts

mniToolbars.add(mncStandard);
mniToolbars.add(mncFormatting);
mniToolbars.add(mncAutoText);

V 1.0 © Aptech Limited


4
Session 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,
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.
Concepts

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:
public JRadioButtonMenuItem(String label)
where,
label: Is the String representing label of the radio button menu item.
Concepts

 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


4
Session 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


mnuView.add(mnrNormal);
Concepts

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)
where,
select: If set to true then JRadioButtonMenuItem is selected. If set to false then
Concepts

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


4
Session 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.
Syntax:
public JMenuItem add(JMenuItem item)
Concepts

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 void setDefaultLightWeightPopupEnabled(boolean
lightweight)
where,
lightweight: If set to true popup becomes light weight popup menu, otherwise not.
The statement JPopupMenu.setDefaultLightWeightPopupEnabled(true); makes the
popup a light weight menu.
Concepts

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


4
Session 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.
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:
Concepts

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);
// Add a Horizontal Glue
mnbBar.add(Box.createHorizontalGlue());
Concepts

// Add the last menu


mnbBar.add(mnuHelp);
frm.setJMenuBar(mnbBar);
frm.setVisible(true);

V 1.0 © Aptech Limited


4
Session 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.
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.


Concepts

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.
int: return type, can be one of the following valid values:
 JFileChooser.CANCEL _ OPTION if you cancel the dialog box.
Concepts

 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


4
Session 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.APPROVE_OPTION and
JFileChooser.ERROR_OPTION.
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:

 public File getSelectedFile()


Concepts

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.
Code Snippet 11:

JFileChooser fcrChooser;
Concepts

File currentDir;
// Creates a file chooser
fcrChooser = new JFileChooser();
// Retrieves the selected directory.
currentDir = fcrChooser.getCurrentDirectory();

V 1.0 © Aptech Limited


4
Session 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.
Figure 4.13 displays the Filter.
Concepts

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


4
Session 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
ImageFilter filter = new ImageFilter();
// Sets the filter
Concepts

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


The getDescription() method return a human readable description of the file name.
Syntax:
Concepts

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


4
Session 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.

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
Concepts

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) {
String extension;
Concepts

String type = null;

V 1.0 © Aptech Limited


4
Session 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;
} else if (extension.equals(“tiff”) || extension.equals(“tif”)) {
icon = tiffIcon;
Concepts

} 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.
Figure 4.16 shows a dockable JToolBar.
Concepts

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:

public class Display extends JFrame


{
Concepts

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)
where,
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.
Concepts

V 1.0 © Aptech Limited


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.
Example: The statement tbrTools.addSeparator(); adds a separator between buttons of a
toolbar.
Concepts

 public void setBorderPainted(boolean paintBorder)


The method is used to paint a border around the toolbar.

V 1.0 © Aptech Limited


4
Session 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.
Example: The statement tbrTools.setOrientation(JToolBar.HORIZONTAL); changes the
orientation of the toolbar to horizontal.

4.5.6 Customizing the Toolbar


Concepts

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:
public void addSeparator ()
Concepts

V 1.0 © Aptech Limited


4
Session 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”));
// Add the open button
Concepts

tbrTool.add(btnOpen);

V 1.0 © Aptech Limited


4
Session 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. Each of the menu items displayed as choices in the menu drop down is associated with
actions to perform desired action.
B. The popup menu provided in GUI is invisible at first sight.
C. The menu bar contains items called menu items.
D. A menu system provides a bar above the window’s title bar called as menu bar.
E. A menu when clicked drops down to display various choices called menu items.

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


(B) C, D, and E (D) A, B, and E
2. 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”);
mniToolbars.add(mncStandard); mniToolbars.add(mncAutoText);
B. JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncAutoText;
mncStandard = new JCheckBoxMenuItem(“Standard”);
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);
add(mncStandard);
add(mncAutoText);
C. JMenuItem mniToolbars;
JCheckBoxMenuItem mncStandard,mncAutoText;
mncStandard = new JCheckBoxMenuItem(“Standard”, true);
mncAutoText = new JCheckBoxMenuItem(“Auto Text”);
Concepts

mniToolbars = new JMenuItem();


mniToolbars.add(mncStandard);
mniToolbars.add(mncAutoText);

V 1.0 © Aptech Limited


4
Session 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”);
mnpPopup.add(mniCopy);
B. JPopupMenu mnpPopup;
JMenuItem mniMark, mniCopy;
mnpPopup = new JPopupMenu();
mniMark = new JMenuItem(“Mark”);
mnpPopup.add(mniMark);
mniCopy = new JMenuItem(“Copy”);
mnpPopup.add(mniCopy);
C. JPopupMenu mnpPopup;
JPopupMenuItem mniMark, mniCopy;
mnpPopup = new JPopupMenu();
mniMark = new JPopupMenuItem(“Mark”);
mnpPopup.add(mniMark);
mniCopy = new JPopupMenuItem(“Copy”);
Concepts

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) C, D, and E (C) B, C, and D


(B) B, D, and E (D) A, C, and D
5. 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;
fcrChooser = new JFilechooser(“C:\\Assignments”);
B. JFileChooser fcrChooser;
fcrChooser = new JFileChooser(“C:\\Assignments”);
C. JFileChooser fcrChooser;
fcrChooser = new JFileChooser(“C:\Assignments”);
D. JFileChoose fcrChooser;
fcrChooser = new JFileChoose(“C://Assignments”);

6. Which of the statements about JToolBar are true?


Concepts

A. A JToolBar is similar to a menu and contains buttons with icons.


B. A dockable toolbar is also called as a floatable toolbar.
C. A JToolBar is dockable only if the container it belongs has a BorderLayout.
D. A JToolBar is dockable means you cannot drag it to another location.
E. A JToolBar serves the same purpose as a JMenuBar.

V 1.0 © Aptech Limited


4
Session Menu Components

(A) B and C (C) B and E


(B) C and D (D) A and C
7. Can you match the methods of JToolBar against their description?

Method Descriptions
(A) addSeparator() 1. Makes toolbar dockable.
(B) setFloatable() 2. Displays border around the toolbar.
(C) add() 3. Changes the orientation.
(D) setBorderPainted() 4. Adds separator between buttons.
(E) setOrientation() 5. Adds a button.

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

V 1.0 © Aptech Limited


4
Session Menu Components

4.6.1 Answers
1. D
2. C
3. B
4. A
5. C
6. C
7. A

Concepts

V 1.0 © Aptech Limited


4
Session 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 Description
Swatches To select a color from a collection of swatches.
HSB By specifying the Hue, Saturation, and
Brightness.
RGB 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 Description Example


public Creates a JColorChooser with the /* Creates a
JColorChooser() initial color as white. JColorChooser
instance using
default constructor
*/
JColorChooser
ccrColors;
// Creates a
colorchooser
ccrColors = new
Concepts

JColorChooser();

V 1.0 © Aptech Limited


5
Session Lists and Panes

Constructor Description Example


public ColorChoo Creates a JColorChooser with the /* creates a
ser(Colorinitial specified initial color. JColorChooser
Color) 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


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.
Concepts

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
frmColorChooser.getContentPane().add(ccrChoser); Concepts

V 1.0 © Aptech Limited


5
Session Lists and Panes

Figure 5.1 shows the output for Code Snippet 1.

Figure 5.1: Output - JColorChooser

5.1.4 Event Handling


To handle the events of JColorChooser, perform the following steps:

Retrieve ColorSelectionModel
Concepts


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


Concepts

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


5
Session 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);
}
});

Figure 5.2 shows the output for Code Snippet 4.


Concepts

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 Description Example


C o l o r The method returns the currently selected JColorChooser
getColor() color. ccrChooser;

Syntax: Color clrColor;


// Creates a color
public Color getColor()
chooser
ccrChooser = new
where, JColorChooser();
Color: Returns an object of class Color // Retrieves the
representing the currently selected color. current
// color selected
clrColor =
ccrChooser.
getColor();
void setColor The method sets the specified color to be the // Set blue as the
(Color) current color. current color

Syntax: JColorChooser
ccrChooser;
public void setColor(Color color)
// Creates a color
chooser

where, ccrChooser = new

color: is an object of class Color representing JColorChooser();


the color to be set. // Sets blue as the
// current color
ccrChooser.setColor
(Color.blue);
Concepts

V 1.0 © Aptech Limited


5
Session Lists and Panes

Method Description Example


ColorshowDial The method displays the standard color /* Displays the
og(Component, dialog box. standard
String, Color)
Syntax: color dialog box with
the title ‘Choose a
public static Color Color’ with red color
showDialog(Component parent, selected initially.
String title, Color initialColor) */
Color clrColor =
JColorChooser.
where, owDialog(null,”Choose
parent: Is the top-level container to which a Color”, Color.red);
this dialog box belongs.
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
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.
Concepts

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 Description Example


public JList() Creates an empty list. // Creates an empty
list
JList lstCountries =
new JList();
public JList(Object[] Creates a list initialized with the items /* Create and
items from the Object array. initialize the string
array with the names
Syntax: of countries */
public JList(Object[] items) String[]
strCountries =
where, {“Australia”,
items: Is an array of objects containing “Belgium”, “Canada”,
Concepts

the items to be displayed in the list. . . . . “India”};


...
// Creates a list with
a string array
JList lstCountries =

V 1.0 © Aptech Limited


5
Session Lists and Panes

Constructor Description Example


=new
List(strCountries);
public JList(Vector Creates a list initialized with items /* Create a list
vecItems) from a vector. with a Vector */
Syntax:
public JList(Vector JList lstCountries
vecItems) = 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
JList lstCountries = new JList(vecCountries);
Concepts

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;
JScrollPane scpScroller;
String[] strCountries;
Concepts

...
// 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


5
Session 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 Description Example


public void This method sets the selection /* Sets the single
SelectionMode(int mode for the list, where selection mode in the
selectMode) selection mode determines how list */
the items are selected. Items JList lstCountries;
Concepts

are selected as single, multiple


. . .
selections contiguously, or in
any order.
selectMode: Is one of the
predefined values of the
selection mode.

V 1.0 © Aptech Limited


5
Session Lists and Panes

Method Description Example


SINGLE_SELECTION: 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
items in any order, this is the
default mode.
public void This method sets the layout of This method sets the layout of
setLayoutOrientation(int the cells in the list. the cells in the list.
layoutOrient) layoutOrient: Is one of layoutOrient: Is one of
the predefined values of the predefined values of
orientation. orientation.
JList.VERTICAL: The JList.VERTICAL: The
columns are displayed columns are displayed
vertically. 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 This method sets the number of /* Display four rows
setVisibleRowCount(int rows to be displayed in the list in the list without
count) without scrollbars. scrollbars */
JList lstCountries;
. . .
int count = 4;
Concepts

lstCountries.
setVisibleRowCount
(count);

Table 5.5: Methods to Configure JList

V 1.0 © Aptech Limited


5
Session Lists and Panes

 Getting Data from JList


Some of the methods to get data from JList are listed in table 5.6.

Method Description Example


public void This method is used to clear the lstCountries.
clearSelection() selection of the items from the list. clearSelection();
public int This method returns index of the int index = lstCountries.
selected item as an integer value. tSelectedIndex();
getSelected
The index is zero-based.
Index()
public int[]getSel This method returns an array of int[] indices =
ectedIndices() indices of selected items. The array lstCountries.
containing the indices of multiple electedIndices();
items selected.
public boolean This method returns true if no boolean selected
isSelectionEmpty() item is selected. = lstCountries.
isSelectionEmpty();

public Color This method returns the background JList lstCountries;


getSelect color of the selected item, which is String[] strCountries
represented by the instance of the = {“Australia”,
ionBackground() Color class. “Belgium”, “Canada”, . .
. . “India”};
lstCountries =
new JList
(strCountries);
/* Retrieve the
background color
of selection
Color */
clrBackground =
lstCountries.
getSelection
Background();
Concepts

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 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.
public void This method is used to select multiple items
setSelectedIndices(int[] programmatically.
indices)
public void setSelectionBackgr This method sets the background color of the selected
ound(Color c) 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


strCountries = new String[20];
Concepts

// Initialize the array with names of countries.


...
// Sets the items in the list
lstCountries.setListData(strCountries);

V 1.0 © Aptech Limited


5
Session 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.

Figure 5.6: Output - Code Snippet 7

5.2.4 Event Handling


Concepts

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 Description
Register a To handle the events of a JList, you register a
ListSelectionListener 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)
{
// Adds the action code
Concepts

...
}
});

V 1.0 © Aptech Limited


5
Session 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 Description Example


public JComboBox() JComboBox cboFonts = new
Creates an empty combo box.
JComboBox();
public JComboBox(Object[] Creates a combo box with the /* Create and initialize
items) items contained in the Object a string array with 10
array. elements*/
String[] strFonts =
{“Arial”, ”Times New
Roman”,. . . . ”Verdana”};
/* Create a combo box with
the items from string array
*/
JComboBox cboFonts = new
JComboBox(strFonts);
Concepts

V 1.0 © Aptech Limited


5
Session Lists and Panes

public JComboBox(Vector Creates a combo box with the /* Creates a vector to


items) items contained in the vector. store the font names 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 shows a JComboBox with the list of items.

Figure 5.7: JComboBox


Concepts

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


5
Session 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);
// Adds the combo box to the panel pnlFonts.add(cboFonts);
Concepts

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:
public void addActionListener(ActionL
istener e)
where,
Concepts

e: Is an object of any class which implements the


ActionListener interface.
Add the action code in Whenever the item in the combo box is selected,
actionPerformed() the actionPerformed() method is invoked, you
method add the action code in this method

V 1.0 © Aptech Limited


5
Session 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.
Syntax:
public void addItemListener(ItemListener e)
Concepts

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)
{
// SELECT event
Concepts

...
} else
{
// DESELECT event

V 1.0 © Aptech Limited


5
Session Lists and Panes

. ..
}
});
}

5.3.5 Methods of JComboBox


The important methods of a JComboBox are listed in table 5.12.

Method Description
public void addItem(Object item) 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 New
Roman”);
public int getItemCount() The method returns the number of items in the
JComboBox.
Example: int count = cboFonts.
getItemCount();
public int getSelectedIndex() The method returns an integer representing the
index of the item selected.
Example: int index = cboFonts.
getSelectedIndex();
public Object getSelectedItem() 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();

public void setEditable(boolean This method is used to make the JComboBox


editable) editable.
Example: cboFonts.setEditable(true);
Concepts

public void setSelectedIndex(int This method is used to select an item


index) programmatically.
Example: cboFonts.setSelectedIndex(2);

V 1.0 © Aptech Limited


5
Session Lists and Panes

Method Description
public void setSelectedItem(Object This method is used to select an item
item) programmatically. The object to be selected from
the list of items available is specified.
Example: cboFonts.
setSelectedItem(“Times New Roman”);
public Object getItemAt(int index) 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 = new
JComboBox(strFonts);
// Retrieve the item at index 1
String strFontName = (String)cboFonts.
getItemAt(1);
public int getMaximumRowCount() 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 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);
Concepts

/* Retrieve the maximum number of row


count */
int rowCount = cboFonts.
getMaximumRowCount();

V 1.0 © Aptech Limited


5
Session Lists and Panes

Method Description
public Object[] The getSelectedObjects() method of
getSelectedObjects() 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”;
cboFonts.insertItemAt(strNewName,1);
public void removeAllItems() 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);
Table 5.12: Methods of JComboBox

5.4 JTabbedPane
Concepts

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.

Constructor Description Example


public JTabbedPane() Creates an empty JTabbedPane JTabbedPane
with the default tab placement tpnProperties;
on top. tpnProperties = new
JTabbedPane();
public JTabbedPane(int Creates an empty JTabbedPane JTabbedPane
Concepts

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


5
Session 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 Description
void addTab(String title, Component The method adds a component with the specified
component) title. The argument title is a string specifying
the title of the tab. The argument component is
the component to be displayed.
void addTab(String title, Icon icon, The method adds a component with the specified
Component component) title and icon. The argument icon specifies an
image.
void addTab(String title, Icon icon, The method adds a component with the specified
Component component, String tip) title, icon, and the tool tip.
Concepts

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”);
// Adds panel having the title “English”, icon and tooltip to tabbedpane
tpnSubjects.addTab(“English”,iconEnglish,pnlEnglish, “English Subject”);
Concepts

// Adds the tabbedpane to the frame


frmSubjects.getContentPane().add(tpnSubjects);

V 1.0 © Aptech Limited


5
Session Lists and Panes

5.4.3 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;
...
// Register the ChangeListener tpnSubjects.addChangeListener(new
ChangeListener() {
Concepts

// 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.
A JSplitPane is created using any one of the constructors listed in table 5.16.

Constructor Description
Concepts

JSplitPane() The method creates a JSplitPane with the


components placed side by side with no continuous
layout.
JSplitPane(int) The method creates a JSplitPane with the
specified orientation and no continuous layout.

V 1.0 © Aptech Limited


5
Session 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.
JSplitPane(int, boolean) 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.
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);

Figure 5.12 shows the output for Code Snippet 14.


Concepts

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.HORIZONTAL_SPLIT places the two components side by side.
The orientation JSplitPane.VERTICAL_SPLIT places the two components one below the other.
Concepts

V 1.0 © Aptech Limited


5
Session 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
e(true);
void setDividerLocation(int) 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.
Concepts

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 Z-
order 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.

Figure 5.16: JLayeredPane

Note: JDesktopPane is a JLayeredPane subclass that is used specifically of holding internal frames.
Concepts

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


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 Description
FRAME_CONTENT_LAYER At level 30000 for holding the menu bar and the content
pane.
PALETTE_LAYER Level 0 to hold normal components.
MODAL_LAYER Level 100 for holding floating toolbars and the similar
components.
POPUP_LAYER Level 300 for holding popup menus and tooltips.
DRAG_LAYER Level 400 to ensure the dragged objects remain on top.
Table 5.18: Constants Defined for JLayeredPane
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:
Concepts

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 Description
addImpl() 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, Object
constraints, int index)
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)
where,
c: Is the component whose index is returned.
Concepts

V 1.0 © Aptech Limited


5
Session Lists and Panes

Method Description
moveToFront() 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,
c: Is the component to be moved.
setPosition() 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.

Table 5.19: Methods of JLayeredPane


Concepts

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. Registering an ActionListener to handle the event of a JComboBox is preferred


over ItemListener.
B. A JComboBox is a combination of a drop-down and a TextField.
C. ActionListener can trap events of new item being selected and the previous item
being deselected.
D. The method addItemListener() is used to register the ItemListener event handler.
E. The JComboBox allows you to type a new item which is not available in the drop-
down.

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


(B) C, D, and E (D) B, D, and E
2. 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 = new JComboBox(strFonts); cboFonts.
setEditable(true);
pnlFonts.add();
B. JPanel pnlFonts = new JPanel();
String[] strFonts = new String[10];
...
...
JComboBox cboFonts = new JComboBox(strFonts); cboFonts.
setEditable(false); pnlFonts.add(cboFonts);
C. JPanel pnlFonts = new JPanel();
String[] strFonts = new String[10];
Concepts

...
...
JComboBox cboFonts = new JComboBox(); cboFonts.
setEditable(true); pnlFonts.add(cboFonts);

V 1.0 © Aptech Limited


5
Session 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. A ChangeListener object cannot be registered with a JTabbedPane.


B. Each component added to JTabbedPane has a tab, which can have a textual label or
an icon.
C. In JTabbedPane, several panels can be clubbed together to occupy the same space
in the GUI.
D. The addTabPane() method is used to add a tab to JTabbedPane.
E. The default tab placement of a JTabbedPane is top.

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


(B) C, D, and E (D) A, C, and D
4. 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;
. . .
ImageIcon iconEnglish = new ImageIcon(“background.gif”);
tpnProperties.addTab(“Background”,pnlBackground,iconEnglish);
B. JPanel pnlBackground;
JTabbedPane tpnProperties;
. . .
ImageIcon iconEnglish = new ImageIcon(“background.gif”);
tpnProperties.add(“Background”,pnlBackground,iconEnglish);
C. JPanel pnlBackground;
JTabbedPane tpnProperties;
Concepts

. . .
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. The two components in the JSplitPane can be displayed horizontally (side by side)
or vertically (one below the other).
B. JSplitPane cannot dynamically change the sizing requirements per component
basis.
C. The left component is displayed at the right or bottom.
D. The right component is displayed at the left or top.
E. The divider can be dragged to specify how much of the total area is to be given to a
component.

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


(B) A and E (D) A, C, and D
6. 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;
frmExplorer = new JFrame(“Explorer”);
spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
Concepts

false); spnExplorer.setDividerLocation(200); frmExplorer.


getContentPane().add(spnExplorer);

V 1.0 © Aptech Limited


5
Session Lists and Panes

(D) JFrame frmExplorer; JSplitPane spnExplorer;


frmExplorer = new JFrame(“Explorer”);
spnExplorer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true); spnExplorer.setDividerLocation(2000); frmExplorer.
getContentPane().add(spnExplorer);
Concepts

V 1.0 © Aptech Limited


5
Session Lists and Panes

5.7.1 Answers
1. D
2. D
3. C
4. D
5. B
6. B

Concepts

V 1.0 © Aptech Limited


5
Session 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.

Constructor Description Example


public JTable() Creates a JTable with a default JTable tblReports = new
table model with no initial data JTable();
or column.
public JTable(int Creates a JTable with the int rows = 10;
Concepts

numRows, int numColumns) specified rows and columns with


int cols = 5;
no initial data or columns.
JTable tblReports;
tblReports = new
JTable(rows, columns);

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

Constructor Description Example


public JTable(Object[][] Creates a JTable with the JTable tblReports;
data, Object[] columns) specified arrays data and
String[][] data;
columns.
String[] columns;

// Initialize columns
array
. . .
// Initialize data array
. . .
tblReports = new
JTable(data, columns);
public JTable(Vector Creates a JTable with the JTable tblReports;
data, Vector columns) specified vectors data and Vector data;
columns.
Vector columns;

// Initialize the
columns
// vector
. . .
// Initialize the data
vector
. . .
tblReports = new
JTable(data, columns);
public JTable(TableModel Creates a JTable with the JTable tblReports;
model) specified table model. ReportTableModel
The argument, model is an rptModel;// Inner class
// which extends //
object of any class which
AbstractTableModel
implements the TableModel
Concepts

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.
Code Snippet 1:
Concepts

JFrame frmReports;
JTable tblReports;
Vector vecData;
Vector vecColumns;

V 1.0 © Aptech Limited


6
Session 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


The main drawbacks of JTable are as follows:

 All columns are of the same width by default.


Concepts

 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.
Syntax:
public boolean print() throws PrinterException
Concepts

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


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
where,
printMode: specifies the mode of printing, the valid values are JTable.FIT_WIDTH and
Concepts

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, MessageFormatheader,
MessageFormat footer) throws PrinterException;
where,
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.
Concepts

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


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)
{

System.out.println(“Exception : “ + ex.getMessage());
}
Concepts

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.

6.1.7 AbstractTableModel Interface


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.
Concepts

Table 6.2 lists the methods that need implementation in case of AbstractTableModel.

Method Description
public int Returns the number of rows. In case the data is a two
getRowCount() dimensional array, the attribute length is returned.

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

Method Description
public int Returns the number of columns. In case the column
getColumnCount() 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
public void setData(Object[][] data)
{
Concepts

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 = {“…”, “…”};
...
// Instantiate the data model reportTable with the data and columns from
Concepts

// 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


6
Session 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 Description Example


Register a MouseListener The addMouseListener() // Register the mouse
method is used to register listener to the reports
MouseListener object to table tblReports.
addMouseListener(new
handle mouse events. This
Concepts

MouseAdapter() {
method takes an object of
a class which implements // provides
the MouseListener, as an implementation to the
argument. Typically an anonymous mouse clicked event
class of MouseListener or a });
MouseAdapter is used.

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

Steps Description Example


Add the action code in Both MouseListener and // Register the mouse
mouseClicked() method MouseAdapter have a method listener to the reports
mouseClicked(), which is table tblReports.
addMouseListener(new
invoked as a result of the mouse
MouseAdapter() {
being pressed and released.
This method takes an object of // Provide implementation
MouseEvent class as argument. 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.

Display Description
The file system on an operating system The file system includes the drive, its root folder
and the sub folders.
Concepts

Organizational hierarchy The hierarchy includes the top management,


middle management and all other staff.
Ancestry details The details include ancestors and their
predecessor.
Table 6.4: JTree Display

V 1.0 © Aptech Limited


6
Session 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.
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.
Concepts

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 Description Example


Create an instance of The javax.swing.tree DefaultMutableTreeNode
DefaultMutableTreeNode package has the class dmtnRoot;
DefaultMutableTreeNode dmtnRoot= new DefaultMut
to represent a root node, ableTreeNode(“Root”);
branch-node or a leaf-node.
To represent the root node,
you create an instance of a
DefaultMutableTreeNode
class.
Create an instance of a JTree Create an instance of a JTree DefaultMutableTreeNode
and pass the root node as an dmtnRoot; JTree treTree;
Concepts

argument in the constructor // Creates an instance


of a JTree: public of a JTree with the root
JTree(TreeNode node). node as an argument
treTree= new
JTree(dmtnRoot);

Table 6.5: Steps to Create JTree

V 1.0 © Aptech Limited


6
Session 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);

// Adds the JScrollPane to the frame frmTree.getContentPane().add(scpScroller);


Concepts

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 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.
Add code in the valueChanged() method 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 shows how to register tree selection listener to the JTree.
Code Snippet 9:
Concepts

JTree treTree;
// Registers the tree selection listener to the tree treTree.addTreeSelectionList
ener(new TreeSelectionListener() {
. . .});

V 1.0 © Aptech Limited


6
Session 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 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.
Add code in the treeExpanded() Whenever a node of a tree expands the method
method treeExpanded() is invoked. You write the action code
to handle the node expansion event in this method.
Add code in the treeCollapsed() Whenever a node of a tree collapses the method
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;
...
treTree.addTreeExpansionListener(new TreeExpansionListener() {
...
Concepts

});

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 Examples


Register a ATreeWillExpandListener JTree treTree;
TreeWillExpand object is registered to handle this . . .
Listener event.
treTree.addTreeWillExpandL
The addTreeWillExpand istener(new TreeWillExpand
Listener() method is Listener()
used to add an object of any
Concepts

class which implements the


TreeWillExpandListener
interface.

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

Steps Description Examples


Add code in the Whenever a node of a tree is about //Register the tree will
TreeWillExpand() to expand the treeWillExpand() expand listener treTree.ad
method method is invoked. You write the dTreeWillExpandListener(ne
w TreeWillExpandListener()
action code to handle the node
{
expansion event in this method.
public void treeWillExpand
(TreeExpansionEvent e)
Add code in the Whenever a node of a tree TreeWillExpandListener() {
treeWillCollapse() is about to collapse the public void
method treeWillCollapse() method is treeWillCollapse
invoked. You write the action code (TreeExpansionEvent e)
to handle the node collapse event in
this method.
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.
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.
Concepts

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


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:

 JColorChooser

 JEditorPane

 JFileChooser

 JFormattedTextField

 JList

 JTable

 JTextArea
Concepts

 JTextField

 JTextPane

V 1.0 © Aptech Limited


6
Session 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 Description
TransferHandler() This creates TransferHandler for subclasses.
TransferHandler(String property) This method creates a TransferHandler
Concepts

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;
JButton button;

public DragAndDropDemo() {
Concepts

setTitle(“Built-in Drag and Drop”);


setLayout(new GridLayout(1, 2));

// Creates an array and initializes the JList

V 1.0 © Aptech Limited


6
Session 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();
}
}

Figure 6.10 shows the output of the Code Snippet 14.


Concepts

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) This method is used to query what actions are supported
by the source component, such as COPY, MOVE, or
LINK, in any combination.
createTransferable(JComponent) This method bundles up the data to be exported into a
Transferable object in preparation for the transfer.
exportDone(JComponent, This method is invoked after the export is complete.
Transferable, int) 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) {
c.removeSelection();
}
Concepts

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


6
Session 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){}

6.3.7 Implementation of DND


Before a Drag and Drop operation is fired, it is necessary to create Drag sources, Drop targets, drag
Concepts

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


6
Session 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
...
tblReports = new JTable(data,columns);
Concepts

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

2. Which of these statements about JTable are true?

A. The JTable makes all the columns of same width by default.


B. Horizontal scrolling will be activated because of ellipsis.
C. If the data changes then the new data is not reflected in the table.
D. Only the last few characters with “…” appended is displayed in smaller width column.
E. You have to instantiate the table again to reflect the data changes.

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


(B) C, D, and E (D) A, C, and D
3. Can you match the features of JTable against their description?

Features Description
(A) DefaultTableModel (1) Return number of rows
(B) getColumnCount() (2) Return number of columns
(C) getValueAt() (3) Abstract implementation
(D) getRowCount() (4) Concrete implementation
(E) AbstractTableModel (5) Return data at specified row and
column

(A) A-4, B-2, C-5, D-1, E-3 (C) A-2, B-4, C-3, D-1, E-5
(B) A-3, B-5, C-4, D-1, E-2 (D) A-5, B-2, C-4, D-1, E-3
4. 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


6
Session Advanced Swing Components

(C) tblReports.addMouseListener(new MouseAdapter { public void


mouseClicked(MouseEvent me) {
// Click code
. . .}
});
(D) tblReports.addMouselistener(new MouseAdapter() { public void
mouseClicked(MouseEvent me) {

// Click code
. . .
}
});

5. Which of the following statements about JTree are true?

(A) A JTree displays data vertically, each row contains only one item called node.
(B) Every JTree has a root node at the bottom.
(C) Initially, except the root node, all branch-nodes are in a collapsed state.
(D) Nodes which have children are called branch-nodes.
(E) A leaf-node can expand and collapse.

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


(B) C, D, and E (D) A, C, and D
6. 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);
JScrollPane scpScroller = new JScrollPane(dmtnBranch1);
frmTree.getContentPane().add(scpScroller);
Concepts

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

(B) 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 = new JScrollPane(dmtnRoot);
frmTree.getContentPane().add(scpScroller);
(D) 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 Events
(A) treeCollapsed() (1) Node of a tree is selected
(B) valueChanged() (2) Node of a tree collapses
(C) treeExpanded() (3) Node of a tree expands
(D) treeWillExpand() (4) Node of a tree is about to collapse
(E) treeWillCollapse() (5) Node of tree is about to expand

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

V 1.0 © Aptech Limited


6
Session Advanced Swing Components

6.4.1 Answers
1. C
2. A
3. A
4. B
5. D
6. D
7. C
Concepts

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
7
Session 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 accept-
able 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 transla-
tor 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


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.
Concepts

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.
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.
Concepts

V 1.0 © Aptech Limited


7
Session Internationalization

Figure 7.2 displays an example of localization.

Figure 7.2: Example of Localization

7.1.4 Benefits of I18N and L10N


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
Concepts

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

7.1.6 Significance of Unicode


The Java platform uses Unicode as its native character encoding. However, Java programs still need to
Concepts

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


7
Session 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


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.
Concepts

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.
Inquiry = How are you?
MessageBundle_fr_FR.properties Greetings = Bonjour.
farewell = Au revoir
inquiry = allez-vous?
MessageBundle_de_DE.properties 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:

Constructor Description Example


public Creates Locale object with the specified /* Creates Locale
Locale(String language and country. object for English
language, String language and US
country) Here, language argument is the language country */
code consisting of two letters in lowercase
Locale
and country argument is the country code
usLocale = new
consisting of two letters in upper case. Locale(“en”,”US”);
public Creates a Locale object in the specified /* Creates Locale
Locale(String language. object for English
language) language */
Concepts

Locale enLocale =
new Locale(“en”);

Table 7.2: Locale – Constructor Methods

V 1.0 © Aptech Limited


7
Session Internationalization

7.2.4 Locale Class Methods


Some of the important methods of the Locale class are listed in table 7.3.

Method Description Example


public static Locale Gets the default Locale for the /* Retrieve the default
getDefault() instance of the JVM. Locale for the JVM */
Locale currentLocale =
Locale.getDefault();
public final String Returns the name of the country /* Retrieve the country
getDisplayCountry() for the current Locale, which name in a user-friendly
is appropriate for display to the format */
user. For example, if the default Locale currentLocale =
locale is fr_FR, this method will Locale.getDefault();
return France.
String strCountry =
currentLocale.
getDisplayCountry();
public final String Returns the name of the /* Retrieve the language
getDisplayLanguage() language for the current Locale, name in a user-friendly
in an appropriate format to the format */
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.

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.
Concepts

Example: To retrieve the available locales.


Locale [] locales;
locales = Locale.getAvailableLocales();

V 1.0 © Aptech Limited


7
Session Internationalization

Method Description
public String This method returns an uppercase letter code for the country/region
getCountry() 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
String country = locale.getCountry();
public String This method returns a lowercase letter code for the country or region
getLanguage() 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
String language = locale.getLanguage();
public final String The getDisplayName() method is used to retrieve a name for the
getDisplayName() 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
String name = locale.getDisplayName();
Concepts

V 1.0 © Aptech Limited


7
Session Internationalization

Method Description
forLanguageTag () 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(“ja-
Japan”);

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 three-
letter 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 Code
English En
Arabic Ar
German De
Table 7.5: Language Codes
Table 7.6 lists a few of the examples for country codes.

Country Code
United States US
Concepts

Canada CA
France FR
Japan 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 (French-
speaking 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 Language Support


Arabic Arabic
Chinese (simplified) Chinese
Chinese (traditional) Chinese
Hebrew Hebrew
Japanese Japanese
Korean 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.
This information allows you to write applications that can be:
Concepts

 Localized or translated into different languages

 Handled for multiple locales at the same time

 Supported for more locales later

V 1.0 © Aptech Limited


7
Session 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 ResourceBun-
dle class is initialized with a valid language and country matching the available properties file.
Syntax:
public static final ResourceBundle getBundle(String baseName, Locale lo-
cale)
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 Locale object with the language French and
country
// France
currentLocale = new Locale(language, country);
// Retrieves the locale-specific information
messages = ResourceBundle.getBundle(“MessagesBundle”, currentLocale);

7.2.9 Fetching the Text from ResourceBundle Class


Concepts

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 Description
public abstract The getKeys() method returns an enumeration object
Enumeration<String> representing all the available keys in the properties file.
getKeys()

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:

Enumeration bundleKeys = messages.getKeys();


Concepts

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


7
Session 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() 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.
public final String[] The static method getStringArray() is used to retrieve
getStringArray(String key) a string array for the specified key from the resource bundle
or one of its parents.
Example:
// Retrieves the resource bundle for the
// default
locale ResourceBundle messages =
Concepts

ResourceBundle.getBundle(“MessagesBundle”);
String[] values = messages.getStringArray(“g
reetings”);

V 1.0 © Aptech Limited


7
Session Internationalization

Method Description
protected void The static method setParent() is used to set the parent
setParent(ReourceBundle bundle of a resource bundle object. The parent bundle is
parent) 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);
...
...
// Retrieves the resource bundle for the default locale messages = ResourceBundle.
getBundle(“MessagesBundle”);
// Retrieve the locale of the resource bundle Locale locale = messages.
getLocale();
Concepts

// 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


7
Session 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.
Figure 7.6 displays the need for formatting.
Concepts

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 Description


Numbers getNumberInstance() 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.
Currencies getCurrencyInstance() 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.
Percentages getPercentInstance() 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;
String strPercent;
// Creates a Locale object with language as French and country
Concepts

// 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


7
Session 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);
System.out.println(format);
Concepts

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

7.3.4 Date and Time


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.
Concepts

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


7
Session 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: DateFor-
mat.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;
String strDate;
DateFormat dateFormatter;
Concepts

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,
dateStyle: It is an int which specifies the date formatting style. Valid values include: DateFormat.
SHORT, DateFormat.MEDIUM, DateFormat.LONG, and DateFormat.FULL
Concepts

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


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.
Code Snippet 13:
Concepts

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.
Figure 7.9 displays formatting of messages. Concepts

Figure 7.9: Formatting Messages

V 1.0 © Aptech Limited


7
Session 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 The first step involves writing down the message and
identifying all the variable parts of the message.
Create a template 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.
Create an Object array for variable For each variable part in the template, a value is
arguments 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.
Create a MessageFormat instance The next step is to create a MessageFormat
instance and set the desired locale. The locale is
Concepts

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 creates an Object array for the template.
Code Snippet 15:
Concepts

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


7
Session Internationalization

3. 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 mes-
sage:
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 Description
MessageFormatBundle.properties disk = D:
template = At {2,time,short} on {2,date,long},
we detected {1,number,integer} virus on the disk {0}
MessageFormatBundle _ fr _ template = À {2,time,short} {2,date,long}, nous avons
FR.properties disk = D détecté le virus {1,number,integer} sur le disque {0}
MessageFormatBundle _ de _ template = Um {2,time,short} an
DE.properties disk = D {2,date,long}, ermittelten wir Virus
{1,number,integer} auf der Scheibe {0}

Table 7.12: Properties File

7.3.12 ParsePosition Class


Concepts

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
pos = new ParsePosition(0);

Concepts

V 1.0 © Aptech Limited


7
Session Internationalization

7.4 Check Your Progress


1. Which of the following statements about Internationalization are true?

A. Internationalized software is developed separately for each country and language.


B. Successful translation of the source files in the desired language is very difficult.
C. Cost of development of the product in the desired language will be much lower than
the one time cost.
D. Internationalized software should be developed such that it can be adapted without
engineering changes.
E. Internationalization is the process of designing an application, so that it can adapt to
various regions.

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


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

2. Which of the following statements about Localization and its benefits are true?

A. The translation of text is the least time-consuming part of the localization process.
B. Localization is the process of adapting software for a specific region.
C. Textual elements are stored outside the source code and retrieved dynamically.
D. Textual elements such as labels and messages for GUI components are hard-coded in
the program.
E. Support for new languages requires recompilation.

(A) B and E (C) B and C


(B) D and E (D) C and D

3. 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.
Concepts

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 (C) B and D


(B) D and E (D) C and E

V 1.0 © Aptech Limited


7
Session Internationalization

4. 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 (C) A, B, and D


(B) C and E (D) C and D

5. 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);
messages=ResourceBundle.getBundle(“MessagesBundle”,
currentLocale);
B. String language = “fr”; String country = “FR”; Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(country, language);
messages=ResourceBundle.getBundle(“MessagesBundle”,
currentLocale);
C. String language = “fr”; String country = “FR”; Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle(“MessagesBundle”,
currentLocale);
D. String language = “fr”;
String country = “FR”;
Locale currentLocale; ResourceBundle messages;
Concepts

currentLocale = new Locale(language, country);


messages = ResourceBundle.getBundle(currentLocale,
”MessagesBundle”);

V 1.0 © Aptech Limited


7
Session Internationalization

6. 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();
System.out.println(“key = “ + key + “, “ + “value = “ + value);
B. Enumeration bundleKeys = messages.getKeys();
while(bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = messages.getString(key);
System.out.println(“key = “ + key + “, “ + “value = “ + value);
C. Enumeration bundleKeys = messages.getKeys();
while(bundleKeys.hasMoreElements()) {
String key = bundleKeys.nextElement();
String value = messages.getString(key);
System.out.println(“key = “ + key + “, “ + “value = “ + value);
D. 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?

A. The getCurrencyInstance() returns an instance of a NumberFormat class


initialized to the specified locale.
B. The argument passed can only be primitive data type.
C. The getCurrencyInstance() takes an instance of Locale class as an argument.
Concepts

D. The date and time format need not conform to the conventions of the end user’s
Locale.
E. 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 (C) A and D


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

8. 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.

(A) B (C) B and D


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

Concepts

V 1.0 © Aptech Limited


7
Session Internationalization

7.4.1 Answers
1. B
2. C
3. D
4. D
5. C
6. C
7. A
8. A
Concepts

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


7
Session Internationalization
Concepts

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
8
Session 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 four-
layered 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 This layer deals with opening
Datagram Protocol) 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.

Table 8.1: TCP Layers

8.1.2 Communication on Computers


Concepts

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.

8.1.5 Networking Basics


A computer generally has a single physical connection available for the network. The physical connections
Concepts

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


8
Session 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
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.
Concepts

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 iden-
tifier 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
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
Concepts

V 1.0 © Aptech Limited


8
Session 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 Description
URL(String url) Constructs an absolute URL object with the specified string
representing a valid URL.
URL(String protocol, Constructs an absolute URL object with the specified protocol,
String host, String file) host, and the resource file.
URL(String protocol, Constructs an absolute URL object with the specified protocol,
String host, int port, host, port, and the resource file.
String file)
URL(URL baseURL, String The first argument specifies the base of the new URL. The
relativeURL) 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
Concepts

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)
{
System.out.println(“Exception : “ + e.getMessage());
Concepts

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 Description
public String This method returns the host name of the URL. This method
getHost() returns the IP address enclosed in square brackets.
public String This method returns the file name of the URL. If the URL has a
getFile() query string attached, then the query string is also concatenated
and returned.
public String This method returns only the path of the URL. If the URL has a
getPath() query string, they are not returned.
public final Opens a connection to a URL and returns an InputStream for
InputStream reading from that connection. The InputStream returned can
openStream() be wrapped within a BufferedReader to read directly from the
URL.
public String The getQuery() method is used to retrieve the query part of
getQuery() the URL. A “?” delimits the URL and the query part. The query
part contains name=value, pair, multiple pairs are delimited with
the ‘&’ sign.
public final The getContent() method is used to retrieve the contents of
Object the URL.
getContent()
public int The getDefaultPort() method is used to retrieve the default
getDefaultPort() port associated with the given URL.
Concepts

public String The getProtocol() method is used to retrieve the protocol


getProtocol() 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();
System.out.println(“File Name : “ + strFile);
}catch(MalformedURLException ex) { System.out.println(“Exception : “ +
ex.getMessage());
Concepts

V 1.0 © Aptech Limited


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 URL(“http://java.sun.com/docs/books/tutorial/
index. html”);
// 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);
// Closes the BufferedReader reader.close();
catch(MalformedURLException ex)
Concepts

{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 = url.
getDefaultPort();
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.

Method Description
public String This method returns the raw IP address in textual format.
getHostAddress()
public String This method returns the host name of the IP address.
getHostName()
public static This method returns an IP address of the local host.
InetAddress
getLocalHost()
public static This method returns an IP address of the specified host name. The
InetAddress
Concepts

host name can either be a machine name, such as “java.sun.com”,


getByName(String or a textual representation of its IP address. If the specified host
host)
is a literal IP, only the validity of the address format is checked.

V 1.0 © Aptech Limited


8
Session Networking

Method Description
Static The getAllByName() method returns an array of InetAddress.
InetAddress[] The array represents all of the addresses that a particular name
getAllByName resolves. The method. will throw an UnknownHostException if it
(String name)
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.
Concepts

Code Snippet 14:


try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException ex) { ex.printStackTrace();

V 1.0 © Aptech Limited


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


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
Concepts

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 If the openConnection() method of the URL class is executed
openConnection() successfully, a reference to the URLConnection object is returned.
method If the openConnection() method fails to execute, an IOException
is raised.
Retrieve the The InputStream object is retrieved from the URLConnection
InputStream from object. This object is wrapped within a BufferedReader object to
the connection read directly from the URL.
Retrieve the The OuputStream object is retrieved from the URLConnection
OutputStream from object. This object is wrapped within a BufferedWriter object to
the connection 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 url = null; try {
url = new URL(“http://www.yahoo.com/”); URLConnection urlCon = url.
openConnection();
Concepts

} catch (MalformedURLException ex) { ex.printStackTrace();


} catch (IOException ex) { ex.printStackTrace();
}

V 1.0 © Aptech Limited


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 Description
public The getContentType() method is used to retrieve the content
getContentType() 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.
Concepts

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 = urlCon.
getContentType();
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:
...
int contentLength; try {
Concepts

// 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


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:
int timeOut; try {
// Creates and instantiates URL object
Concepts

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.

Figure 8.4: Socket

8.4.2 Creating a Socket


Concepts

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


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 Unknown-
HostException. 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();
}

Figure 8.5 displays the socket creation.


Concepts

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 Description
Retrieve the The Socket class has a method getInputStream() which returns an
InputStream from the InputStream object associated with a host’s socket. This object is
socket normally wrapped in a BufferedReader object, for directly reading
data from the socket.
Retrieve the The Socket class has a method getOutputStream() which returns
OutputStream from an OutputStream object associated with a host’s socket. This
the socket object is normally wrapped in a PrintStream or PrintWriter object
for writing data to the socket.
Read from the Once a BufferedReader object is created, you use the readLine()
InputStream method to read from the socket until a null is encountered which
indicates that all data sent from the host has been read.
Write to the Once a PrintStream or PrintWriter object is created, you use the
OutputStream 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 (UnknownHostException ex) { ex.printStackTrace();
} catch (IOException ex) { ex.printStackTrace();
Concepts

V 1.0 © Aptech Limited


8
Session 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
while((strInfo = reader.readLine()) != null) {
Concepts

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
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.
ServerSocket class creates servers that listen for local or remote client programs that connect to them
Concepts

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


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.
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.
Concepts

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 Description
getInetAddress() 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.
close() The close() method is used to close the server socket.
isBound() The is Bound() method is used to retrieve the binding state of
the server socket.
getLocalPort() 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
Concepts

bound.
Code Snippet 31:

V 1.0 © Aptech Limited


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.”);
} catch(IOException ex) {
System.out.println(“Exception : “ + ex.getMessage());
Concepts

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());
}
...
Concepts

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


8
Session 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
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
Concepts

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.

Constructors Description
DatagramSocket(int) Constructs a datagram socket and binds it to the specified port
on the local host machine.
Concepts

DatagramSocket(int, Constructs a datagram socket bound to the local address specified


InetAddress) 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


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();
}
catch (IOException ex)
Concepts

{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


8
Session 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 The method returns the IP address of the machine to which the
getAddress() datagram packet is being sent or received.
public int getPort() The method returns the port number of the remote host to which
the datagram packet is being sent or received.
public byte[] The method returns the data buffer. The data received or the
getData() data to be sent starts from the offset in the buffer, and continues
till the specified length. By default the offset is zero.
public void The method sets the data buffer for the packet. The offset is set
setData(byte[] data) to zero, and the length of data is set to the length of the data
array.
public void The method sets the port number on the remote host to which
setPort(int port) 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:
// Creates buffer of size 256 bytes byte[] buf = new byte[256];
// Creates a DatagramPacket object
Concepts

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.
Code Snippet 44:
final int PORT = 5000;
Concepts

// 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


8
Session 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();
InetAddress group = InetAddress.getByName(“204.0.115.0”);
Concepts

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);
String received = new String(packet.getData());
System.out.println(“Quote of the Moment: “ + received);
Concepts

}socket.leaveGroup(group);
socket.close();

V 1.0 © Aptech Limited


8
Session 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.

Constructor Description
MulticastSocket() Creates a Multicast Socket
Concepts

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 Description
getInterface() Retrieves the network address used for multicast packets.
getLoopbackMode() 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.
Table 8.15: Methods of MulticastSockets
Concepts

 getInterface()
Code Snippet 50 shows how to retrieve the network address used for multicast packets.
Code Snippet 50:

V 1.0 © Aptech Limited


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()
Code Snippet 52 show how to get the setting for local loopback of datagrams.
Code Snippet 52:
Concepts

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();
try { if (ttl != dttl) {
} getImpl().send(p);
Concepts

V 1.0 © Aptech Limited


8
Session 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();
soc.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
Concepts

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(“InetAddress: %s\n”, inetAddress);
} out.printf(“\n”); }}
Concepts

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


8
Session 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
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
Concepts

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 shows how to create and set a system-wide CookieManager.
Concepts

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


8
Session 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.
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.
Concepts

V 1.0 © Aptech Limited


8
Session Networking

8.9 Check Your Progress


1. State whether the following statements about networking are true.

A. TCP is a connection-based protocol that provides a reliable transfer of data between


two computers.
B. You do not write programs at the lower level like application, instead you generally
program at the transport level.
C. Java provides the java.net package which contains all the necessary classes to perform
system-independent network communications.
D. TCP guarantees that data sent from one end of the connection is received at the other
end.
E. The top most layer in the TCP protocol is the network layer.

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


(B) C, D, and E (D) A, C, and D
2. 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. A computer generally has a single physical connection available for the network.
D. The physical connection is logically numbered within a range of 0 to 65500.
E. Data transmitted over the Internet is accompanied with the destination address.

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


(B) B, C, D, and E (D) A, C, and D
3. 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. The format of the resource name depends on the protocol being used.
Concepts

D. In resource name, port number to which you connect has to be specified.


E. URL is a reference or an address to a resource on the Internet.

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


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

V 1.0 © Aptech Limited


8
Session Networking

4. 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() (3) Opens a connection to the URL


(D) getLocalHost() (4) Retrieves the host name of the URL
(E) getHostAddress() (5) Retrieves the file name of the URL.

(A) A-5, B-3, C-4, D-1, E-2 (C) A-5, B-3, C-1, D-2, E-4
(B) A-4, B-3, C-5, D-1, E-2 (D) A-2, B-3, C-1, D-4, E-5
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.
C. If the openConnection() method of the URL class is executed successfully, a
reference to the IOException object is returned.
D. If the openConnection() method fails to execute, an URLConnection object is
returned.
E. Instances of URLConnection class can be used to read from and to write to the resource
referenced by the URL.

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


(B) C and D (D) D and E
Concepts

V 1.0 © Aptech Limited


8
Session Networking

8.9.1 Answers
1. D

2. C
3. A
4. A
5. A

Concepts

V 1.0 © Aptech Limited


8
Session 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

9.1.1 RMI
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
Concepts

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


9
Session 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


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.
Concepts

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 (method-
Concepts

bodies) 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


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 {
}

 Declare the remote methods signatures


All the methods which are meant to be remotely invoked are declared in the remote interface. Re-
mote clients can only invoke these methods. Methods from other interfaces which are non-remote
Concepts

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
}
Code Snippet 3 shows how to qualify the remote method to throw a RemoteException.

Concepts

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 { }

 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 cli-
ent invocations. Only the methods declared in the remote interfaces are exposed to the client for
Concepts

remote invocations.
Syntax:
public class ImplementationClassName extends UnicastRemoteObject imple-
ments 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 im-
plementation of all method signatures from the remote interfaces.
Syntax:
public Return-type methodName(Parameters if any) throws RemoteException
{ }
Code Snippet 7 shows the implementation of the remote method from the HelloInterface.
Concepts

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();

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
Concepts

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 registry = LocateRegistry.getRegistry();
registry.bind(“Hello”, stub);
Concepts

V 1.0 © Aptech Limited


9
Session 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


The RMI client requires the stub which is the remote object reference to invoke the methods re-
motely. 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:
Concepts

RemoteInterface remoteObject = (RemoteInterface) Naming.lookup(String


name);

V 1.0 © Aptech Limited


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
System.out.println(strResult);

9.3.8 Executing RMI Applications


Concepts

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


9
Session 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
Naming.rebind(name, remoteObject);
Concepts

...
...
// Unbind the name bound in the registry

V 1.0 © Aptech Limited


9
Session 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
HelloServerImpl remoteObject = new HelloServerImpl();
// Retrieve the registry
Concepts

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 Registry getRegistry(String host, int port) 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.
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”;
final int PORT = 5000;
try {
Concepts

// Create an instance of the implementation class


HelloServerImpl remoteObject = new HelloServerImpl();
// Retrieve the registry

V 1.0 © Aptech Limited


9
Session 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 {
// Create an instance of the implementation class
Concepts

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 unexportObject(Remote obj, boolean force) throws
NoSuchObjectException
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 shows how to unexport a remote object.
Code Snippet 18:
Concepts

Registry registry;
String name = “rmi://localhost:1099”;
try {
// Create an instance of the implementation class

V 1.0 © Aptech Limited


9
Session 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


1. Which of the following statements about RMI are true?

A. A Java application can only invoke the methods of the classes available inside its JVM.
B. Distributed computing revolves around client-server technology.
C. RMI does not allow a Java program running inside a JVM to execute a method of a class
available in another JVM.
D. Java provides the java.rmi package which contains all the necessary classes and
interfaces to support distributed computing in Java.
E. 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 (C) A, B, and D


(B) C, D, and E (D) A, C, and D
2. Which of the following statements about RMI are false?

A. Socket Programming can serialize and transmit objects.


B. RMI takes into account the byte order during serializing
C. Socket Programming is a low level technology.
D. Windows and UNIX have the same byte order in the machine architecture.
E. RMI does not allow you to serialize and transmit objects.

(A) B and C (C) A and D


(B) D and E (D) C and D
3. Can you match the descriptions against features of RMI architecture?

Features Description
(A) Stub and Skeleton Layer (1) Sets the connections
(B) Remote Reference Layer (2) Converting data into on-the-wire format
(C) Transport Layer (3) Transmitting and receiving data
(D) Marshalling (4) Converting on-the-wire format into data
(E) Unmarshalling (5) Invocation of the remote method.

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

(B) A-3, B-5, C-1, D-2, E-4 (D) A-2, B-3, C-1, D-4, E-5
4. Which of the following statements about components of RMI are true?

A. The java.rmi.Remote interface serves to distinguish interfaces which are non-


remote.
B. A RMI application has to expose methods, which remote clients can invoke.

V 1.0 © Aptech Limited


9
Session 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 (C) A, B, and D


(B) A, B, and C (D) A, C, and D
5. 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 Remote Method Invocation

6. 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();
Naming.rebind(name);
B. String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();
Naming.rebind(remoteObject);
C. String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();
Naming.rebind(name, remoteObject);
D. String name = “rmi://localhost:1099/HelloServer”;
HelloServerImpl remoteObject = new HelloServerImpl();
Naming.rebind(name,remoteObject);

Concepts

V 1.0 © Aptech Limited


9
Session Remote Method Invocation

9.7.1 Answers
1. A
2. A
3. B
4. B
5. A
6. D
Concepts

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


10
Session 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.
Figure 10.1 shows the use of JavaMail API to manage mails on the mailing system.
Concepts

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


10
Session 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
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.
Concepts

 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


10
Session 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


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.
Concepts

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


10
Session 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 shows how to retrieve a default session object with the getDefaultInstance()
method.
Code Snippet 2:
Concepts

String mailhost = “gmail.websolutions.com”;


// Retrieve the system properties
Properties props = System.getProperties();

V 1.0 © Aptech Limited


10
Session 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.*;
import java.net.InetAddress;
Concepts

// Authenticator for requesting password information


public class GMAILAuthenticator extends Authenticator {
String username;
String password;

V 1.0 © Aptech Limited


10
Session 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();
}
...
Concepts

 public static Session getInstance(Properties prop, Authenticator auth)


The getInstance() method is used to retrieve a new Session object.

V 1.0 © Aptech Limited


10
Session 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


10
Session 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
Concepts

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


10
Session 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


10
Session 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:

...
try {
...
Concepts

Address[] addresses = {new InternetAddress(“mike@gmail.com”), new


InternetAddress(“alex@gmail.com”) };
Session session = Session.getInstance(props, null);

V 1.0 © Aptech Limited


10
Session 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”;
String strTo = “mails.mike@gmail.com”;
String strCc = “alex@gmail.com”;
Concepts

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


10
Session 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());
}
...

10.2.5 How to Use MimeMessage


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
Concepts

and contents.

V 1.0 © Aptech Limited


10
Session 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);
// Construct the message
Message msg = new MimeMessage(session);
Concepts

} catch(MessagingException ex) {
System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited


10
Session 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
Concepts

text, then the content type of the message needs to be set.


Syntax:
public void setContent(Object content,String type)throws
MessagingException

V 1.0 © Aptech Limited


10
Session 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
msg.setText(strText);
} catch(MessagingException ex) {
Concepts

System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited


10
Session 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
Message msg = new MimeMessage(session);
Concepts

V 1.0 © Aptech Limited


10
Session 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


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.
Concepts

V 1.0 © Aptech Limited


10
Session 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”
public InternetAddress(String address, boolean strict)throws
AddressException
where,
Concepts

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


10
Session 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[] parse(String addressList) throws
AddressException
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,
false);
} catch(AddressException ex) {
Concepts

System.out.println(“Exception : “ + ex.getMessage());
}

V 1.0 © Aptech Limited


10
Session 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
where,
msg: is an object of the Message class.
Concepts

V 1.0 © Aptech Limited


10
Session 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.
Syntax:
Concepts

public static void send(Message msg, Address[] addresses) throws


MessagingException
where,
msg: is an object of the Message class.

V 1.0 © Aptech Limited


10
Session 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());
}

10.2.11 Store
A mail service provider maintains a store which contains the folder where your messages are kept. To
Concepts

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


10
Session 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
props.put(“mail.transport.protocol”, “pop3”);
// Set the port to 995
Concepts

props.setProperty(“mail.pop3.port”, “995”);
try {
// Retrieve the session instance

V 1.0 © Aptech Limited


10
Session 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 host,String user,String password)throws
MessagingException
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”);
// Set the port to 995
props.setProperty(“mail.pop3.port”, “995”);
Concepts

try {
// Retrieve the session object with properties
Session session = Session.getInstance(props);
// Retrieve the store

V 1.0 © Aptech Limited


10
Session 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()
where,
int: is an integer which specifies the open mode of the folder. The valid values are Folder.
Concepts

READ_ONLY and Folder.READ_WRITE.

V 1.0 © Aptech Limited


10
Session 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”);
// Open the folder in read only mode
folder.open(Folder.READ_ONLY);
Concepts

// Retrieve the open mode


openMode = folder.getMode();
if (openMode == Folder.READ_ONLY) {

V 1.0 © Aptech Limited


10
Session 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”;
String strUser = “johnk@aptech.ac.in”;
Concepts

String strPass = “WinJohn400”;


int openMode;
Store store;
try {
// Retrieve the session instance with the desired attributes

V 1.0 © Aptech Limited


10
Session 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:


Concepts

 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


10
Session 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.
Syntax:
public abstract Folder getFolder(String name) throws MessagingException
Concepts

where,
name: is a String which represents the folder name like INBOX.

V 1.0 © Aptech Limited


10
Session 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
where,
mode: is an integer which specifies the mode of operation, valid values are Folder.READ_
Concepts

ONLY or Folder.READ_WRITE.

V 1.0 © Aptech Limited


10
Session 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:
public Message[] getMessages() throws MessagingException
where,
Concepts

Message: is an array of the Message class containing the messages.

V 1.0 © Aptech Limited


10
Session 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
This exception is raised if the message cannot be sent to any of the recipients.
Concepts

V 1.0 © Aptech Limited


10
Session 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”;


String strTo = “mike@gmail.com”;
String strFrom = “mails.vincent.com”;
Concepts

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


10
Session 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
msg.setSubject(strSubject);
// Set the message text as plain text
Concepts

msg.setText(strText);
// Set the current date

V 1.0 © Aptech Limited


10
Session 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;
JPasswordField pswPassword;
String strHost = “pop.gmail.com”;
Concepts

String strUser = txtUserName.getText().trim();


String strPass = pswPassword.getText().trim();
Store store = null;

V 1.0 © Aptech Limited


10
Session 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++) {
// Retrieve subject of the message
String subject=msgs[i].getSubject();
Concepts

System.out.println(“Subject : “ + subject); }

V 1.0 © Aptech Limited


10
Session 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 MessagingExcep-
tion
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 {
Message message;
// TextArea to display and edit the message text
Concepts

JTextArea txaText;
int index;

V 1.0 © Aptech Limited


10
Session 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


10
Session JavaMail

10.4 Check Your Progress


1. Which of the following statements about JavaMail API are true?

A. The JavaMail API is part of the core package.


B. The JavaMail API is used to read, compose, and send electronic messages.
C. The MUA type of program depends on the MTA types to handle the actual delivery.
D. The JavaMail provides a means to develop protocol-independent access for sending
and receiving mails.
E. The JavaMail API is responsible for the actual transporting, delivering, and forwarding
messages.

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


(B) C, D, and E (D) A, C, and D
2. Can you match the descriptions of mail protocols against their features?

Feature Description
(A) SMTP (1) Supports multiple folders for each user
(B) POP (2) Defines content type of the message
(C) IMAP (3) API
(D) MIME (4) Delivering of email
(E) JavaMail (5) Supports a single mailbox

(A) A-4, B-5, C-1, D-2, E-3 (C) A-5, B-4, C-2, D-3, E-1
(B) A-4, B-5, C-1, D-3, E-2 (D) A-2, B-3, C-5, D-1, E-4
3. 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);
Session session = Session.getDefaultInstance(props);
B. String mailhost = “gmail.websolutions.com”;
Properties props = System.getProperties();
Concepts

props.put(“mail.smtp.host”, mailhost);
Session session = Session.getInstance(props);

V 1.0 © Aptech Limited


10
Session JavaMail

C. String mailhost = “gmail.websolutions.com”;


Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailhost);
Session session = Session.getInstance();
D. 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. The javax.mail.Message class is used to create messages.


B. The javax.mail.Message class implements a Part interface.
C. The session object is created from message object.
D. The date and subject are parts of the message object.
E. The Part interface which specifies the attributes and content type of the message.

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


(B) C, D, and E (D) B, D, and E
5. Can you arrange the steps to create a message object using the MimeMessage in sequence?

A. Set the content of the message


B. Set the attributes required
C. Create an empty message object from a session
D. Create a session object
E. Set the content type of the message
(A) A, B, C, D, E (C) B, C, D, E, A
(B) E, D, C, A, B (D) D, C, B, E, A Concepts

V 1.0 © Aptech Limited


10
Session JavaMail

6. 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,
strCc);
}
Concepts

catch(AddressException ex) {
System.out.println(“Exception : “ + ex.getMessage();
}

V 1.0 © Aptech Limited


10
Session 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. The javax.mail.Store class represents a message store of the message.


B. The argument passed in the getStore() method can be POP3 or IMAP protocol.
C. To get a connection to the store you pass only user id as the authentication parameter.
D. To retrieve a message from email service, you have to gain access to the store first.
E. The Store class inherits the method getStore() from the super class Service

(A) A (C) B
(B) C (D) D

Concepts

V 1.0 © Aptech Limited


10
Session JavaMail

10.4.1 Answers
1. C
2. A
3. A
4. D
5. D
6. A
7. D
Concepts

V 1.0 © Aptech Limited


10
Session 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

Вам также может понравиться