Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Global Academy of Technology

Department of Computer Science and Engineering


IV Semester B.E –Object Oriented Concepts (17CS42)
Module 5
The Applet Class, Swings
APPLETS:
Java applications are stand-alone Java programs that can be run by using just the Java interpreter,
for example, from a command line.
Java applets, however, are run from inside a World Wide Web browser. A reference to an applet is
embedded in a Web page using a special HTML tag. When a reader, using a Java-aware browser,
loads a Web page with an applet in it, the browser downloads that applet from a Web server and
executes it on the local system. Because Java applets run inside the Java browser, they have access
to the same capabilities that the browser has: sophisticated graphics, drawing, and image
processing packages; user interface elements; networking; and event handling.

Life Cycle of Applet

Different methods that are used in Applet Life Cycle:


1. init() Method: This method is intended for whatever initialization is needed for your applet.
It is called after the param tags inside the applet tag have been processed.
2. start() method: This method is automatically called after the browser calls the init()
method. It is also called whenever the user returns to the page containing the applet after
having gone off to other pages.
3. stop() method: This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
4. destroy() method: This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally leave
resources behind after a user leaves the page that contains the applet.
5. paint() method: Invoked immediately after the start() method, and also any time the applet
needs to rent itself in the browser. The paint() method is actually inherited from the
java.awt.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 1 of 44


Two Types of Applets
1) The first type of applet is based directly on the Applet class. These applets use the Abstract
Window Toolkit (AWT) to provide the graphic user interface (or use no GUI at all). This style of
applet has been available since Java was first created.
2) The second type of applets are those based on the Swing class JApplet. Swing applets use the
Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface than
does the AWT. Thus, Swing-based applets are now the most popular.
Because JApplet inherits Applet, all the features of Applet are also available in JApplet.

Applet Basics
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone
programs. Instead, they run within either a web browser or an applet viewer. appletviewer, is
provided by the JDK. Execution of an applet does not begin at main( ). Instead, execution of an
applet is started and controlled with an entirely different mechanism.

To use an applet, it is specified in an HTML file. One way to do this is by using the APPLET tag. The
applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within
the HTMLfile. To view and test an applet more conveniently, simply include a comment at the
head of your Java source code file that contains the APPLET tag.
Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a window that is
200 pixels wide and 60 pixels high.

The Applet Class


Applet provides all necessary support for applet execution, such as starting and stopping. It also
provides methods that load and display images, and methods that load and play audio clips.

Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component.
These classes provide support for Java’s window-based, graphical interface.

Some of the methods provided by applet class are:


1. void destroy( ): Called by the browser just before an applet is terminated. Your applet will
override this method if it needs to perform any cleanup prior to its destruction.
2. AccessibleContext getAccessibleContext( ) :- Returns the accessibility context for the invoking
object.
3. AppletContext getAppletContext( ) :- Returns the context associated with the applet.
4. String getAppletInfo( ) :- Returns a string that describes the applet.
5. AudioClip getAudioClip(URL url) :- Returns an AudioClip object that encapsulates the audio clip
found at the location specified by url.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 2 of 44


Applet Architecture
An applet is a window-based program.
First, applets are event driven. An applet resembles a set of interrupt service routines. Here is how
the process works. An applet waits until an event occurs. The run-time system notifies the applet
about an event by calling an event handler that has been provided by the applet. Once this
happens, the applet must take appropriate action and then quickly return. This is a crucial point.
For the most part, your applet should not enter a “mode” of operation in which it maintains
control for an extended period. Instead, it must perform specific actions in response to events and
then return control to the run-time system.
Second, the user initiates interaction with an applet—not the other way around. The user
interacts with the applet as he or she wants, when he or she wants. These interactions are sent to
the applet as events to which the applet must respond. For example, when the user clicks the
mouse inside the applet’s window, a mouse-clicked event is generated

An Applet Skeleton
All but the most trivial applets override a set of methods that provides the basic mechanism by
which the browser or applet viewer interfaces to the applet and controls its execution. Four of
these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by
Applet. Applets do not need to override those methods they do not use.AWT-based applets will
also override the paint( ) method, which is defined by the AWT Component class. This method is
called when the applet’s output must be redisplayed.

These five methods can be assembled into the skeleton shown here:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;

/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/

public class AppletSkel extends Applet


{
// Called first
public void init() {
// initialization
}

/* Called second, after init(). Also called whenever


the applet is restarted. */
public void start() {
// start or resume execution
}

// Called when the applet is stopped.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 3 of 44


public void stop() {
// suspends execution
}

/* Called when applet is terminated. This is the last


method executed. */
public void destroy() {
// perform shutdown activities
}

// Called when an applet's window must be restored.


public void paint(Graphics g) {
// redisplay contents of window
}
}

Applet Initialization and Termination


When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

 init()
The init( ) method is the first method to be called. This is where variables are initialized. This
method is called only once during the run time of applet.

 start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each
time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes
back, the applet resumes execution at start( ).

 paint( )
The paint( ) method is called each time applet’s output must be redrawn. This situation can occur
for several reasons. For example, the window in which the applet is running may be overwritten
by another window and then uncovered. Or the applet window may be minimized and then
restored. paint( ) is also called when the applet begins execution.Whatever the cause, whenever
the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of
type Graphics.

 stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop( ) is called, the applet is probably
running

SUNIL M R, CSE, GAT 15CS45: Object-Oriented Concepts Page 4 of 44


 destroy()
The destroy( ) method is called when the environment determines that applet needs to be
removed completely from memory. At this point, any resources the applet may be using should be
freed. The stop( ) method is always called before destroy( ).

 Overriding update( )
In some situations, applet may need to override another method defined by the AWT, called
update( ). This method is called when your applet has requested that a portion of its window be
redrawn. The default version of update( ) simply calls paint( ).

Simple Applet Display Methods


To output a string to an applet, use drawString( ), which is a member of the Graphics class.
Typically, it is called from within either update( ) or paint( ). It has the following general form:

void drawString(String message, int x, int y)


Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is
location 0,0.

To set the background color of an applet’s window, use setBackground( ). To set the foreground
color (the color in which text is shown, for example), use setForeground( ). These methods are
defined by Component, and they have the following general forms:

void setBackground(Color newColor)


void setForeground(Color newColor)

Here, newColor specifies the new color. The class Color defines the constants shown here that can
be used to specify colors
Color.black ,Color.magenta, Color.blue ,Color.orange, Color.cyan ,Color.pink ,Color.darkGray
,Color.red etc

The current settings for the background and foreground colors can be obtained by calling
getBackground( ) and getForeground( ), respectively. They are also defined by Component and
are shown here:

Color getBackground( )
Color getForeground( )

Example Program
/* A simple applet that sets the foreground and background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 5 of 44


public class Sample extends Applet
{
String msg;
// set the foreground and background colors.
public void init()
{ setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}

// Initialize the string to be displayed.


public void start() {
msg += " Inside start( ) --";
}

// Display msg in applet window.


public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}

The methods stop( ) and destroy( ) are not overridden, because they are not needed by this
simple applet.

Using the Status Window


In addition to displaying information in its window, an applet can also output a message to the
status window of the browser or applet viewer on which it is running. To do so, call showStatus( )
with the string that needs to be displayed. The status window is a good place to give the user
feedback about what is occurring in the applet, suggest options, or possibly report some types of
errors.
The following applet demonstrates showStatus( ):

// Using the Status Window.


import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.cyan);

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 6 of 44


}

// Display msg in applet window.


public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

Repaint
An applet writes to its window only when its update( ) or paint( ) method is called by the AWT.
This raises an interesting question: How can the applet itself cause its window to be updated
when its information changes? Whenever your applet needs to update the information displayed
in its window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call
to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus, for
another part of your applet to output to its window, simply store the output and then call repaint(
). The AWT will then execute a call to paint( ), which can display the stored information. For
example, if part of your applet needs to output a string, it can store this string in a String variable
and then call repaint( ). Inside paint( ), you will o/p the string using drawString( ).

The repaint( ) method has four forms.


1) void repaint( )
This version causes the entire window to be repainted.
The following version specifies a region that will be repainted:

2) void repaint(int left, int top, int width, int height)


Here, the coordinates of the upper-left corner of the region are specified by left and top, and
the width and height of the region are passed in width and height.
3) void repaint(long maxDelay)
4) void repaint(long maxDelay, int x, int y, int width, int height)
Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( )
is called.

Example program: A Simple Banner Applet

/* This applet creates a thread that scrolls the message contained in msg right to left
across the applet's window. */

import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 7 of 44


public class SimpleBanner extends Applet implements Runnable
{
String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;
// Set colors and initialize thread.

public void init()


{
setBackground(Color.cyan);
setForeground(Color.red);
}

// Start thread public void start()


{
t = new Thread(this); stopFlag = false; t.start();
}

// Entry point for the thread that runs the banner.


public void run()
{
char ch;
// Display banner
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
}
catch(InterruptedException e) { }
}
}

// Pause the banner.


public void stop()
{
stopFlag = true;
t = null;

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 8 of 44


}

// Display the banner.


public void paint(Graphics g)
{
g.drawString(msg, 50, 30);
}
}

Status Window
In addition to displaying information in its window, an applet can also output a message to the
status window of the browser or applet viewer on which it is running. To do so, call showStatus( )
with the string that you want displayed. The status window is a good place to give the user
feedback about what is occurring in the applet, suggest options, or possibly report some types of
errors.

Example program

import java.awt.*;
import java.applet.*;

/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/

public class StatusWindow extends Applet


{
public void init()
{
setBackground(Color.cyan);
}

// Display msg in applet window.


public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 9 of 44


The HTML APPLET Tag

Sun currently recommends that the APPLET tag be used to start an applet from both an HTML
document and from an applet viewer.
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>

 CODEBASE: CODEBASE is an optional attribute that specifies the base URL of the applet
code, which is the directory that will be searched for the applet’s executable class file
(specified by the CODE tag).
 CODE: CODE is a required attribute that gives the name of the file containing your
applet’s compiled .class file.
 ALT: The ALT tag is an optional attribute used to specify a short text message that should
be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets.
 NAME: NAME is an optional attribute used to specify a name for the applet instance.
Applets must be named in order for other applets on the same page to find them by name
and communicate with them. To obtain an applet by name, use getApplet( ), which is
defined by the AppletContext interface.
 WIDTH and HEIGHT: WIDTH and HEIGHT are required attributes that give the size (in
pixels) of the applet display area.
 ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet..
 VSPACE and HSPACE: These attributes are optional. VSPACE specifies the space, in pixels,
above and below the applet. HSPACE specifies the space, in pixels, on each side of the
applet.
 PARAM NAME and VALUE: The PARAM tag allows you to specify applet-specific arguments
in an HTML page. Applets access their attributes with the getParameter( ) method.

Example Program1
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo1" width=300 height=80>
<param name=fontName >

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 10 of 44


</applet>
*/

public class ParamDemo1 extends Applet


{
String fontName;
public void start()
{
fontName = getParameter("fontName");
if (fontName == null)
fontName= "Laura";
fontName = "Hello " + fontName + "!";
}

// Display parameters.
public void paint(Graphics g)
{
g.drawString(fontName, 0, 10);
}
}

Example program2
import java.awt.*;
import java.applet.*;

/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/

public class ParamDemo extends Applet


{
String fontName;
int fontSize;
float leading;
boolean active;

// Initialize the string to be displayed.


public void start()
{
String param;
fontName = getParameter("fontName");

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 11 of 44


if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try
{
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
}
catch(NumberFormatException e)
{
fontSize = -1;
}
param = getParameter("leading");
try
{
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
}
catch(NumberFormatException e)
{
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}

// Display parameters.
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}

getDocumentBase( ) and getCodeBase( )


Java will allow the applet to load data from the directory holding the HTML file that started the
applet (the document base) and the directory from which the applet’s class file was loaded (the
code base). These directories are returned as URL objects by getDocumentBase( ) and
getCodeBase( ).

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 12 of 44


Example program
import java.awt.*;
import java.applet.*;
import java.net.*;

/*
<applet code="Bases" width=300 height=50>
</applet>
*/

public class Bases extends Applet


{
// Display code and document bases.
public void paint(Graphics g)
{
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}

AppletContext and showDocument( )


One application of Java is to use active images and animation to provide a graphical means of
navigating the Web that is more interesting than simple text-based links. To allow your applet to
transfer control to another URL, you must use the showDocument( ) method defined by the
AppletContext interface.

AppletContext is an interface that lets you get information from the applet’s execution
environment. The context of the currently executing applet is obtained by a call to the
getAppletContext( ) method defined by Applet.

Within an applet, once you have obtained the applet’s context, you can bring another document
into view by calling showDocument( ).

There are two showDocument( ) methods.


The method showDocument(URL) displays the document at the specified URL.
The method showDocument(URL, String) displays the specified document at the specified
location within the browser window

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 13 of 44


Example program
/* Using an applet context, getCodeBase(),and showDocument() to display an HTML file.*/

import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="ACDemo" width=300 height=50>
</applet>
*/
public class ACDemo extends Applet
{
public void start()
{
AppletContext ac = getAppletContext();
URL url = getCodeBase(); // get url of this applet
try
{
ac.showDocument(new URL(url+"Test.html"));
}
catch(MalformedURLException e)
{
showStatus("URL not found");
}
}
}

Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the java.applet package.

The AudioClip interface has three methods, including:


public void play(): Plays the audio clip one time, from the beginning.
public void loop(): Causes the audio clip to replay continually.
public void stop(): Stops playing the audio clip.

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The
getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio
file. The audio file is not downloaded until an attempt is made to play the audio clip.

Example program: Write a Java applet which continuously plays an audio clip named
“anthem.wav” loaded from applets parent directory. Provide the necessary HTML file to run this
applet

import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 14 of 44


{
private AudioClip clip;
private AppletContext context; public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}
catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}

public void start()


{
if(clip != null)
{
clip.loop();
}
}

public void stop()


{
if(clip != null)
{
clip.stop();
}
}
}

Now let us call this applet as follows:


<html>
<title>The AudioDemo applet</title>
<hr>
<applet code="AudioDemo.class" width="0" height="0">
<param name="audio" value="anthem.wav">
</applet>
<hr> </html>

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 15 of 44


Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within
the applet, you use the drawImage() method found in the java.awt.Graphics class.

Example Program:
Following is the example showing all the steps to show images:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}
catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar context.
showStatus("Could not load image!");
}
}

public void paint(Graphics g)


{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}

Now let us call this applet as follows:


<html>
<title>The ImageDemo applet</title>
<hr>

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 16 of 44


<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>\

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 17 of 44


Introducing Swing
Swing is a set of classes that provides more powerful and flexible GUI components.

Two Key Swing Features


The two features of swing are:
1. Swing Components Are Lightweight
2. Swing Supports a Pluggable Look and Feel

Swing Components Are Lightweight


Lightweight components means that they are written entirely in Java and do not translate into
platform-specific peers. That is the look and feel of each component is determined by Swing, not by
the underlying operating system.

Lightweight components are rendered using graphics primitives

Lightweight components are more efficient and more flexible.

Swing Supports a Pluggable Look and Feel


Swing Supports a Pluggable Look and Feel because it is possible to “plug in” a new look and feel for
any given component without creating any side effects in the code that uses that component. To use
a specific style, its look and feel is simply “plugged in.” Once this is done, all components are
automatically rendered using that style.

Pluggable look-and-feels offer several important advantages:


 It is possible to define a look and feel that is consistent across all platforms.
 It is possible to create a look and feel that acts like a specific platform. For example, if we
know that an application will be running only in a Windows environment, it is possible to
specify the Windows look and feel.
 It is also possible to design a custom look and feel.
 The look and feel can be changed dynamically at run time.

The MVC Connection


In MVC terminology:
 The model corresponds to the state information associated with the component. For
example, in the case of a check box, the model contains a field that indicates if the box is
checked or unchecked.
 The view determines how the component is displayed on the screen.
 The controller determines how the component reacts to the user. For example, when the
user clicks a check box, the controller reacts by changing the model to reflect the user’s
choice (checked or unchecked). This then results in the view being updated.

By separating a component into a model, a view, and a controller, the specific implementation of
each can be changed without affecting the other two.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 18 of 44


Swing uses a modified version of MVC that combines the view and the controller into a single logical
entity called the UI delegate. For this reason, Swing’s approach is called either the Model-Delegate
architecture or the Separable Model architecture.

To support the Model-Delegate architecture, most Swing components contain two objects.
1. Model – are defined by interfaces. For example, the model for a button is defined by the
ButtonModel interface.

2. UI delegate – are classes that inherit ComponentUI. For example, the UI delegate for a
button is ButtonUI.

Swing’s pluggable look and feel is made possible by its Model-Delegate architecture.

Components and Containers


A component is an independent visual control, such as a push button or slider. In order for a
component to be displayed, it must be held within a container.

A container is a special type of component that is designed to hold group of components.


For example JFrame.
The components in swing are derived from the JComponent class. JComponent inherits the AWT
classes Container and Component.

All Swing’s components are represented by classes defined in package called javax.swing.

The following table shows the class names for Swing components (including those used as
containers).

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 19 of 44


Swing defines two types of containers:
 Top-level containers: These containers do not inherit JComponent but they inherit AWT
classes Component and Container. For example, JFrame, JApplet, JWindow,
and JDialog.

 Lightweight containers: These containers inherit JComponent and can be inside another
container. For example, JPanel

Each top-level container defines a set of panes called the glass pane, the content pane, and the
layered pane.

The glass pane covers all other panes and by default, it is a transparent instance of JPanel. For
example, the glass pane enables us to manage mouse events that affect the entire container (rather
than an individual control)

The layered pane is an instance of JLayeredPane. The layered pane allows components to be
given a depth value. This value determines which component overlays another.

The content pane is the pane to which our application interacts and this is the pane to which we will
add visual components. In other words, when we add a component, such as a button, to a top-level
container, we will add it to the content pane. By default, the content pane is an opaque instance of
JPanel.

SUNIL M R, CSE, GAT 15CS45: Object-Oriented Concepts Page 20 of 44


The Swing Packages

Java Swing’s are used in two types of Java programs:


1. Desktop application
2. Applet

A Simple Swing Application


The following program illustrates simple Swing application.
import javax.swing.*;
class SwingDemo {
SwingDemo()
{
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");

// Give the frame an initial size.


jfrm.setSize(275, 100);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a text-based label.


JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);

// Display the frame.


jfrm.setVisible(true);
}

public static void main(String args[])


{
new SwingDemo();
}
}

To compile the above program, use this command line:


javac SwingDemo.java

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 21 of 44


To run the above program, use this command line:
java SwingDemo

Output

The above program begins by importing javax.swing package because it includes classes that
define JFrame and JLabel which we have used in the program.

Next, the program declares the SwingDemo class and a constructor for that class. The constructor
begins by creating a JFrame, using this line of code:

JFrame jfrm = new JFrame("A Simple Swing Application");

This creates a container called jfrm that defines a rectangular window complete with a title bar;
close, minimize, maximize, and restore buttons as shown above in program output. The title of the
window is passed to the JFrame.

Next, the size of the window is specified with:


jfrm.setSize(275, 100);

Its general form is:

void setSize(int width, int height)

Here, width and height specifies the width and the height of the window.

By default, when a top-level window is closed (such as when the user clicks the close box), the
window is removed from the screen, but the application is not terminated. But if we want the entire
application to terminate when its top-level
window is closed. We call

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The general form of setDefaultCloseOperation( ) is shown here:


void setDefaultCloseOperation(int what)
The value passed in what determines what happens when the window is closed.

The possible values of what are as follows:


JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 22 of 44


The next line of code creates a Swing JLabel component:
JLabel jlab = new JLabel(" Swing means powerful GUIs.");

The JLabel simply displays the text which is passed as argument to the JLabel

The next line of code adds the label to the content pane of the frame:

jfrm.add(jlab);

The general form of add( ) is shown here:


Component add(Component comp)

Here, comp specifies the component to be added to the container.

The last statement in the SwingDemo constructor causes the window to become visible:
jfrm.setVisible(true);

By default, a JFrame is invisible, so setVisible(true) must be called to display the window.

Inside main( ), a SwingDemo object is created, which causes the window and the label to be
displayed.
new SwingDemo();

Event Handling
The event handling mechanism used by Swing is the same as that used by the AWT. This approach is
called the delegation event model.

In many cases, Swing uses the same events as does the AWT, and these events are packaged in
java.awt.event. Events specific to Swing are stored in javax.swing.event.

The following program handles the event generated by a Swing push button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo implements ActionListener
{
JLabel jlab;

EventDemo()
{
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");
jlab = new JLabel("Press a button.");

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 23 of 44


jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
jfrm.add(jlab);
jfrm.setVisible(true);
jbtnAlpha.addActionListener(this);
jbtnBeta.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();

if(str.equals("Alpha"))
{
jlab.setText("Alpha was pressed");
}
if(str.equals("Beta"))
{
jlab.setText("Beta was pressed");
}
}

public static void main(String args[])


{
new EventDemo();
}
}

Output

In the above program:


 java.awt package is imported because it contains the FlowLayout class, which supports
the standard flow layout manager used to lay out components in a frame.
 java.awt.event package is imported because it includes the ActionListener
interface and the ActionEvent class.

Create a Swing Applet


A Swing applet extends JApplet class rather than Applet class. JApplet is derived from
Applet. Thus, JApplet includes all of the functionality found in Applet and adds support for
Swing.

JApplet is a top-level Swing container. Therefore, components are added to JApplet’s content
pane.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 24 of 44


Swing applets use the same four lifecycle methods – init( ), start( ), stop( ), and
destroy( )

Here is an example of a Swing applet


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="MySwingApplet" width=270 height=50>
</applet>
*/
public class MySwingApplet extends JApplet implements ActionListener
{
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
public void init()
{
setLayout(new FlowLayout());
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
jlab = new JLabel("Press a button.");

add(jbtnAlpha);
add(jbtnBeta);
add(jlab);

jbtnAlpha.addActionListener(this);
jbtnBeta.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Alpha"))
{
jlab.setText("Alpha was pressed");
}
if(str.equals("Beta"))
{
jlab.setText("Beta was pressed");
}
}
}
Output:

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 25 of 44


Swing components

The Swing component classes are shown here:

These components are all lightweight, which means that they are all derived from
JComponent class.

JLabel and ImageIcon


JLabel is used to display text and/or an icon. It does not respond to user input. JLabel defines
following constructors:

JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)

Here,
 str specifies the text used for the label;
 icon specifies the icon used for the label;
 align specifies the horizontal alignment of the text and/or icon within the dimensions of
the label. It takes one of the possible values: LEFT, RIGHT, CENTER, LEADING, or TRAILING.

To create icon object use the following constructor in ImageIcon class

ImageIcon(String filename)

Here, filename is image of the icon.

The icon and text associated with the label can be obtained using following methods:
Icon getIcon( )
String getText( )

To set an icon or text associated with the label use the following methods:

void setIcon(Icon icon)


void setText(String str)

Here, icon and str are the icon and text, respectively

The following applet illustrates how to create and display a label containing both an icon and a text

import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 26 of 44


</applet>
*/
public class JLabelDemo extends JApplet
{
public void init()
{
ImageIcon ii = new ImageIcon("france.gif");
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
add(jl);
}
}

Output

JTextField
JTextField is used to create text field. The text in the text field can be edited. JTextField
defines following constructors:

JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

Here,
str specifies text to be initially presented in the text field.
cols is the number of columns in the text field. In otherwords it specifies size of the text field.

JTextField generates events in response to user interaction. For example,


 ActionEvent is triggered when the user presses ENTER.
 CaretEvent is fired each time the caret (i.e., the cursor) changes position. (CaretEvent is
packaged in javax.swing.event)

The following example illustrates JTextField.


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 27 of 44


/*
<applet code="JTextFieldDemo" width=250 height=150>
</applet>
*/

public class JTextFieldDemo extends JApplet implements


ActionListener
{
JTextField jtf;

public void init()


{
setLayout(new FlowLayout());

jtf = new JTextField(15);


add(jtf);

jtf.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
showStatus(jtf.getText());
}
}

In the above program, when the user presses ENTER, an action event is generated. This is handled by
displaying the text in the status window. The output is shown below:

Swing Buttons
Swing defines four types of buttons:
1. JButton
2. JToggleButton
3. JCheckBox
4. JRadioButton

All these buttons are subclasses of the AbstractButton class.

AbstractButton contains the following methods that allow us to control the behavior of
buttons.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 28 of 44


void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)

Here, di, pi, si, and ri are the icons to be used.

The text associated with a button can be read and written via the following methods:
String getText( )
void setText(String str)

Here, str is the text to be associated with the button.

JButton
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or
both to be associated with the push button. Three of its constructors are shown here:

JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)

Here, str and icon are the string and icon used for the button.

When the button is pressed, an ActionEvent is generated.

The following demonstrates an icon-based button. When a button is pressed, the name of that
country is displayed in the label.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/*
<applet code="JButtonDemo" width=250 height=150>
</applet>
*/

public class JButtonDemo extends JApplet implements ActionListener


{
JLabel jlab;

public void init()


{
setLayout(new FlowLayout());

ImageIcon france = new ImageIcon("France.jpg");


JButton jb1 = new JButton(france);
jb1.setActionCommand("France");

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 29 of 44


ImageIcon germany = new ImageIcon("Japan.jpg");
JButton jb2 = new JButton(germany);
jb2.setActionCommand("Japan");

jlab = new JLabel("Choose a Flag");

add(jb1);
add(jb2);
add(jlab);

jb1.addActionListener(this);
jb2.addActionListener(this);

public void actionPerformed(ActionEvent ae)


{
jlab.setText("You selected " + ae.getActionCommand());
}
}

In the above code getActionCommand( ) obtains the action command string associated with
the button. For example, France and Japan w.r.to the above code.

JToggleButton
A toggle button looks just like a push button, but it has two states: pushed and released. That is,
when we press a toggle button, it stays pressed rather than popping back up as a regular push
button does. When you press the toggle button a second time, it releases (pops up). Therefore, each
time a toggle button is pushed, it toggles between its two states.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 30 of 44


JToggleButton is a superclass for two other Swing components namely JCheckBox and
JRadioButton

JToggleButton has the following constructor:

JToggleButton(String str)

This creates a toggle button that contains the text passed in str.

JToggleButton generates
 Action event each time it is pressed.
 Item event when it is pressed in.

The toggle button state can be determined by calling isSelected( ) method (inherited from
AbstractButton) on the button that generated the event. It is shown here:
boolean isSelected( )

It returns true if the button is selected and false otherwise.

Here is an example that uses a toggle button

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/*
<applet code=" JToggleButton" width=250 height=150>
</applet>
*/

public class JToggleButton extends JApplet implements ItemListener


{
JLabel jlab;
JToggleButton jtbn;

public void init()


{
setLayout(new FlowLayout());

jlab = new JLabel("Button is off.");

jtbn = new JToggleButton("On/Off");

add(jtbn);
add(jlab);

jtbn.addItemListener(this);

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 31 of 44


}

public void itemStateChanged(ItemEvent ie)


{
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
}

Output

Check Boxes
The JCheckBox class provides the functionality of a check box. JCheckBox has the following
constructor:

JCheckBox(String str)

It creates a check box that has the text specified by str as a label.

When the user selects or deselects a check box, an ItemEvent is generated.

The following example illustrates check boxes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet implements ItemListener
{
JLabel jlab;
public void init()
{
setLayout(new FlowLayout());

JCheckBox cb1 = new JCheckBox("C");


JCheckBox cb2 = new JCheckBox("C++");

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 32 of 44


JCheckBox cb3 = new JCheckBox("Java");
JCheckBox cb4 = new JCheckBox("Perl");

jlab = new JLabel("Select languages");

add(cb1);
add(cb2);
add(cb3);
add(cb4);
add(jlab);

cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
cb4.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
}

In the above code getItem( ) obtains reference to the JCheckBox that generated the event.
The selected state of a check box is determined by calling isSelected( ) on the JCheckBox
instance.

Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at
any one time.

To create radio buttons we use the following constructor in JRadioButton class.

JRadioButton(String str)

Here, str is the label for the button.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 33 of 44


To create radio button group we use the following constructor in ButtonGroup class
ButtonGroup()

The radio buttons are then added to button group via following method:

void add(AbstractButton ab)

Here, ab is a reference to the button to be added to the group.

The following example illustrates how to use radio buttons

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet implements
ActionListener
{
JLabel jlab;
public void init()
{
setLayout(new FlowLayout());

//creating radio buttons


JRadioButton b1 = new JRadioButton("A");
JRadioButton b2 = new JRadioButton("B");
JRadioButton b3 = new JRadioButton("C");

jlab = new JLabel("Select One");

add(b1);
add(b2);
add(b3);
add(jlab);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

// creating a button group.


ButtonGroup bg = new ButtonGroup();

// Adding radio buttons to the group


bg.add(b1);
bg.add(b2);
bg.add(b3);
}

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 34 of 44


public void actionPerformed(ActionEvent ae)
{
jlab.setText("You selected " + ae.getActionCommand());
}
}

JTabbedPane
JTabbedPane encapsulates a tabbed pane. Selecting a tab causes the component associated with
that tab to come to the forefront.

JTabbedPane defines three constructors. One is default constructor, which


creates an empty control with the tabs positioned across the top of the pane. The other two
constructors specify the location of the tabs, which can be along any of the four sides.

Tabs are added to the pane by calling addTab( ) method. The general form is:
void addTab(String name, Component comp)

Here, name is the name for the tab, and comp is the component that should be added to the tab.

The component added to a tab is a JPanel that contains a group of related components.

The general procedure to use a tabbed pane is outlined here:


1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.

The following example illustrates a tabbed pane.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet
{
JLabel jlab;

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 35 of 44


public void init()
{
JTabbedPane jtp = new JTabbedPane();

jtp.addTab("Cities", new CitiesPanel());


jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());

add(jtp);
}
}

class CitiesPanel extends JPanel


{
public CitiesPanel()
{
JButton b1 = new JButton("New York");
JButton b2 = new JButton("London");
JButton b3 = new JButton("Hong Kong");
JButton b4 = new JButton("Tokyo");

add(b1);
add(b2);
add(b3);
add(b4);
}
}

class ColorsPanel extends JPanel


{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
JCheckBox cb2 = new JCheckBox("Green");
JCheckBox cb3 = new JCheckBox("Blue");

add(cb1);
add(cb2);
add(cb3);
}
}

class FlavorsPanel extends JPanel


{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();

jcb.addItem("Vanilla");
jcb.addItem("Chocolate");

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 36 of 44


jcb.addItem("Strawberry");

add(jcb);
}
}

JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling of another
component.

The component being scrolled can be either an individual component, such as a table, or a group of
components contained within another lightweight container, such as a JPanel. In either case, if the
object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are
automatically provided, and the component can be scrolled through the pane.

JScrollPane has the following constructor:

JScrollPane(Component comp)

The component to be scrolled is specified by comp.

Here are the steps to follow to use a scroll pane:


1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.

The following example illustrates a scroll pane

// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 37 of 44


/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init()
{
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int j = 0; j < 400; j++)
{
jp.add(new JButton("Button " + b));
++b;
}

// Create the scroll pane.


JScrollPane jsp = new JScrollPane(jp);

// Add the scroll pane to the content pane.


add(jsp, BorderLayout.CENTER);
}
}

JList
JList supports the selection of one or more items from a list. JList has the following
constructor:
JList(Object[ ] items)

This creates a JList that contains the items in the array specified by items.

JList is based on two models


 ListModel – defines how access to the list data is achieved.
 ListSelectionModel – defines methods that determine what list item or items are selected.

A JList generates a ListSelectionEvent when the user makes a selection in the list or
changes a selection in the list.

ListSelectionEvent is handled by implementing ListSelectionListener interface.


This listener interface has only one method, called valueChanged( ), which is shown here:

void valueChanged(ListSelectionEvent le)

Here, le is a reference to the object that generated the event.

Both ListSelectionEvent and ListSelectionListener are available in package called


javax.swing.event.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 38 of 44


By default, a JList allows the user to select multiple ranges of items within the list, but you can
change this behavior by calling setSelectionMode( ), which is defined by JList. It is shown
here:

void setSelectionMode(int mode)

Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:

SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION

We can obtain the index of the first item selected, by calling getSelectedIndex( )method,
shown here:

int getSelectedIndex( )
Here, indexing begins at zero. So, if the first item is selected, this method will return 0. If no item is
selected, –1 is returned.

We can obtain the value associated with the selected item by calling getSelectedValue(
)method shown here:

Object getSelectedValue( )

It returns a reference to the first selected value. If no value has been selected, it returns null.

We wrap a JList inside a JScrollPane. So that long lists will be scrollable automatically.

The following applet demonstrates a simple JList, which holds a list of cities. Each time a city is
selected in the list, a ListSelectionEvent is generated, which is handled by the
valueChanged( ) method defined by ListSelectionListener. It responds by obtaining
the index of the selected item and displaying the name of the selected city in a label.

Example:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

/*
<applet code="JListDemo" width=200 height=120>
</applet>
*/

public class JListDemo extends JApplet implements


ListSelectionListener

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 39 of 44


{
JList jlst;
JLabel jlab;
JScrollPane jscrlp;

String Cities[] = { "New York", "Chicago", "Houston",


"Denver", "Los Angeles", "Seattle",
"London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public void init()
{
setLayout(new FlowLayout());

// Create a JList.
jlst = new JList(Cities);

// Set the list selection mode to single selection.


jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

// Add the list to a scroll pane.


jscrlp = new JScrollPane(jlst);

// Set the preferred size of the scroll pane.


jscrlp.setPreferredSize(new Dimension(120, 90));

// Make a label that displays the selection.


jlab = new JLabel("Choose a City");

add(jscrlp);
add(jlab);

// Add selection listener for the list.


jlst.addListSelectionListener(this);
}

public void valueChanged(ListSelectionEvent le)


{
// Get the index of the changed item.
int idx = jlst.getSelectedIndex();

// Display selection, if item was selected.


if(idx != -1)
jlab.setText("Current selection: " + Cities[idx]);
else
jlab.setText("Choose a City");
}
}

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 40 of 44


JComboBox
JComboBox provides a combo box.

A combo box normally displays one entry, but it will also display a drop-down list that allows a user
to select a different entry.

JComboBox has following constructor:

JComboBox(Object[ ] items)

Here, items is an array that initializes the combo box.

JComboBox generates an action event when the user selects an item from the list. It also generates
an item event when the state of selection changes, which occurs when an item is selected or
deselected.

To obtain the item selected in the list is to call getSelectedItem( ) on the combo box. It is
shown here:

Object getSelectedItem( )

The following example demonstrates the combo box.

// Demonstrate JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/

public class JComboBoxDemo extends JApplet implements ActionListener


{
JLabel jlab;
JComboBox jcb;

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 41 of 44


String flags[] = { "France", "Germany", "Italy", "Japan" };

public void init()


{
setLayout(new FlowLayout());

jcb = new JComboBox(flags);


jlab = new JLabel("Select the country");

add(jcb);
add(jlab);

jcb.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String s = (String) jcb.getSelectedItem();
jlab.setText("You have selected " + s);
}
}

JTable
JTable is a component that displays data in rows and columns. We can resize the columns by
dragging the cursor on column boundaries. We can also drag a column to a new position.

Depending on JTable configuration, it is also possible to select a row, column, or cell within the
table, and to change the data within a cell.

JTable has following constructor:

JTable(Object data[ ][ ], Object colHeads[ ])

Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-
dimensional array with the column headings.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 42 of 44


JTable relies on three models
 TableModel – defines things related to displaying data in a two-dimensional format.
 TableColumnModel – specifies the characteristics of a column.
 ListSelectionModel – determines how items are selected

JTable can generate the following events:


 ListSelectionEvent – generated when the user selects something in the table
 TableModelEvent – generated when table’s data changes in some way.

Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

The following example illustrates how to create and use a simple table

import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet
{
public void init()
{
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };

// Initialize data.
Object[][] data = { { "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};

// Create the table.


JTable table = new JTable(data, colHeads);

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 43 of 44


// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);

// Add the scroll pane to the content pane.


add(jsp);
}
}

Q: Difference between AWT and Swings

AWT Swing
AWT stands for Abstract windows
Swing is also called as JFC’s (Java Foundation classes).
toolkit.
AWT components are called
Swings components are called light weight component
Heavyweight component.
AWT components require java.awt
Swing components require javax.swing package.
package.
AWT components are platform Swing components are made in purely java and they are
dependent. platform independent.
This feature is not supported in
We can have different look and feel in Swing.
AWT.
These feature is not available in Swing has many advanced features like JTabel, JTabbed pane
AWT. which is not available in AWT.

SUNIL M R, CSE, GAT 17CS42: Object-Oriented Concepts Page 44 of 44

You might also like