0% found this document useful (0 votes)
133 views18 pages

Ajp Chapter 2

This document provides an introduction to Swing components in Java. It discusses that Swing was created to address deficiencies in AWT's GUI system, such as AWT's reliance on platform-specific code. Swing implements a set of GUI components based on the MVC architecture and provides pluggable look and feel. It describes some key Swing features, including that Swing components are pure Java and do not rely on native peers. The document also lists some core Swing component classes that extend AWT components and provide a richer set of GUI elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views18 pages

Ajp Chapter 2

This document provides an introduction to Swing components in Java. It discusses that Swing was created to address deficiencies in AWT's GUI system, such as AWT's reliance on platform-specific code. Swing implements a set of GUI components based on the MVC architecture and provides pluggable look and feel. It describes some key Swing features, including that Swing components are pure Java and do not rely on native peers. The document also lists some core Swing component classes that extend AWT components and provide a richer set of GUI elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit I

CHAPTER

2 Swings

Syllabus:
Introduction to swing: Swing features, Difference between AWT and Swing.
-

Swing Components: JApplet, lcons and Labels, Text Fields, Combo Boxes
Buttons: The JButton, Check Boxes, Radio Buttons.

Advanced Swing Components: Tabbed Panes, Scroll Panes,Trees, Tables, Progress bar, tool tips.

MVC Architecture.

2.1 Introduction to Swing


As we discussed earlier, a few core AWT components. Now in this unit we will study the swing components and

their relative advantages over the AWT components. Swing implements a set of GUl components that build on MVC
architecture and provide a pluggable look and feel. The Swing components are entirely written in Java code and they are

based on the JDK 1.1 Lightweight UI Framework.

2.1.1 Swing Features

Swing includes the features like:

(i) All the features of AWT

(i) 100% Pure Java certified versions of the existing AWT component set (Button, Scrollbar, Label, etc.).

A rich set of higher-level components (such as tree view, list box, and tabbed panes).
(ii)
not dependent on native peers.
(iv) PureJava design,

(vPluggable Look and Feel.

depend handle their functionality. Therefore they do not require any third
on peers to
Swing components do not
these components are often called "lightweight" components.
party intermediates to use them on any platform. Thus,
that targets a specific platform (i.e. the Java
In general, AWT components are appropriate for simple applet development
for any platform independent targets.
program will run on only one platform); whereas, swing components are preferred
For most any other Java GUI development we want to use Swing components. Also note that the Borland value
added components included with JBuilder, like dbSwing and JBCL (Java Borland Class Library), are based on Swing
components so if you wish to use these components you will want to base your development on Swing.
Advanced Java Programming (MSBTE)
2-2
Swinga Advanced Java Programming (MSBTE) 2-3 Swings

2.2 Origin of Swing 2.4.1 Components


is the class that provides
and when the developers started usino JComponent class is the hierarchy/root class of all swing component classes. JComponent
the actualy was not present. As Aw Jcomponent class gives visual GUI to swing components. JComponent
class inherits AWTs
In first version of Java, swing
AWT defines a basic set of componen pluggable look and teel.

components, they realize the deficiencies in AWT's GUI system. We know that,
Ine I00K dnd Teel
nents,
of Aw
Component idss. nene, We can say that swing components are built on AWT classes. Following Table 2.4.1 is the list

intenace.
limited graphical
AWT components has
classes.
" showing swing component
window, menus, dialogue boxes, applets. But uses native
code resources. Hene
reason behind
this is,AWT components Table 2.4.1: Swing component clas5es
components are purely platform based. The JPanel
heavy-weightcomponents. JApplet JFrame JWindow
they are referred to as
JRadioButton
generate the problem.
Such as: JButton JSpinner JRadioButton
the use of native code requires native peers. These native peers JRootPane
Actually JRadioButtonMenultem JRadioButtonMenultem JInternalFrame
feel and activity of components changes. JDesktopPane
() Because of difference in Operating system environments; look, JDialog JLayer JComponent
as shape of each component is fixed JFormattedTextField| JPasswordField
causes some boundaries to developers. (Such JEditorPane JFileChooser
The use of AWT components
JLabel JList
either rectangular or opaque.) JLayeredPane JColorChooser
JComboBox
JOptionPane JPopupMenu JProgressBar
Look and feel of each component is fixed. (Due to Operating System dependency)
(ii) IScrollPane JSeparator JSlider
JScrollBar
Hence, in 1997
serious solution to these problems of heavy-weight components. JTextArea
Now, the Java team requires a
ISplitPane JTabbedPane JTable
1.1 as a separate library(called JFL: Java Foundation
introduced. It initially available in Java JToolTip
sWing components were was

Class Libraries5. JTextField JTextPane JToolBar


but in Java 1.2, it was fully merged with Java JMenuBar
ubrary), Togglebutton JMenu JMenultem

JTree JViewport
2.3 Differencebetween AWT and Swing all component classes are under javax.swing package. These all class names begin with
Kemember that, swing
Swing
SrNo. AWT capital letter ' .
called as JFC (Java Foundation Classes)
Abstract Window Toolkit. Swing is also
1. AWT stands for components.
2.4.2 Containers
components are light weight
are heavy weight components. (Swing
AWI components therefore do not require third party Swing defines two types of containers.
in native languages, therefore requires Developed in Java itself,
Developed |native peers. () Heavy weight containers
third party native peers. package. (ii) Light weight containers
Requires to import javax.swing The heavyweight Swing
Requires to importjavo.awt package. top-level containers that
containers are
not do inherit JComponent.
components are developed in Java itself, therefore The heavyweight
a top level container must be at top of control
developed in native/Swing JWindow and JDialog. As the name implies
COmponents are containers are JFrame, JApplet, for web
AWT are platform independent. JFrame for standalone applications and JApplet
therefore they are platform/they used top-level containers are
languages hierarchy. The most commonly
application.
dependent. has pluggable look and
feel. container supported by swing
is JPanel,

look steady and static. |Swing components containers do JComponent. The lightweight
inherit and
The lightweight
AWT components
container. The lightweight
containers are often used to organize

|Swing components are


not thread-safe; we need to be careful JLayered Pane
and JRootPane. It is a general purpose
can be contained
within another container (1.e. can
thread-safe. because a lightweight container
AWT components are multithreading. groups of related components that are
while updating a GUl using
controls
manage create subgroups of related
use lightweight containers such as JPanel to
we can
can be of any attractive shape such as be nested). Thus,
Components are generally of rectangle or/Swing components contained within an outer
container.
AWT curved corners.
Circular or with
opaque in shape. are built on foundation of AWT.
i.e. swing 2.4.3 The Top-Level Container
Panes
components are not dependent on Swing|Swing components are
AWT panes. These
panes
AWT class. containers provide three
are derived classes of related of Swing's top level
written in native languages. components container defines a set panes.
components, they are Each top level
to manage the menu bar.
container JRootPane. It also helps
managed by lightweight

2.4 Swing's JComponent and JContainer 1. Glass Pane


transparent instance of JPane! For
it
studied in previous all other panes. By default, is a

User Interface is distributed into two items: components and containers. As we already The glass pane is the top-level pane and covers
container or to paint over any

Swing's are events that affect the entire

components to manage mouse


where pane enables us
independent individual visual control and container is the
area need
example, the glass
if
but it will be available
we
is an directlyY,
chapter, that component we won't need to use the glass pane
components.In order to display any component, othercomponent.
In most cases,
grouped or placed. We can also say that a container is also one of the
A container can also hold other containers and create hierarchy of containes Techknewiad
container.
must be held within a

and containers are described here in brief.


The componen ts
Advanced Java Programming (MSBTE) SWINg
. Layered Pane Advanced Java Programming (MSBTE) 2-5 Swings
to be given a depth
The layered pane allows components Step 1:Call java program
The layered pane is an instance of JLayeredPane. ue.
another. Thus, the layered pane lets you specify a Z-order fo
This value determines which component overlays Let's call Program 2.5.1 as JFrameDemo.java
hold the content pane a
that we usually need to do. The layered pane and
component, although this is not something
Step 2: Compile and execute program
menu bar.
Swing programs are Compiled and executed in the same way as other AWT programs. Hence compile Program 2.5.1
3. Content Pane
will interactthe most, because this is the pane to which
as follows
The content pane is the pane with which your application
such as a button, to javacJFrameDemo.java
In other words, when you add a component,
you will add visual components (AWT or swing).
default, the content pane is an opaque instance of
top-level container, you will add it to the content pane. By Step3: Run program
JPanel.
Run this program as

2.5 Swing Components java JFrameDemo

In this section, we will discuss on some of the commonly used Swing component classes witn their overloaded Step 4:Output

constructors and methods. On successful compilation the swing program also generates bytecodes (class files). When Program 2.5.1 is
executed it shows following output:
2.5.1 JFrame

We know that swing programs arevery much different


from AWT based programs and console based programs. Demonstrating Swing9
web applications. To study more on swing, it is better to understand a
desktop applications and
Using swing we can create

Swing program and discuss.

of JFrame as top-level window and JLabel as its component.


program to show the
use
Program 2.5.1 Write a

import javax.swing.";
Swing has pluggable look and feel
import java.awt.";
class JFrameDemo extends JFrame

publie JFrameDemo()

Container et = getContentPane( }; Explanation:


JLabel jl =
new JLabel("Swing has pluggable look and feel"); As Program 2.5.1 contains some core swing concepts, we will discuss this one by one, line by line.

cLaddg);
import javax.swing.
imports javax.swing classes. Here we import it for JFrame and Jlabel.
public static void main(String ar[ })
import java.awt.";

it for Container
JFrameDemo fd = new JFrameDemo( ); imports java.awt classes. Here we import

fd.setTile"Demonstrating Swing"): Container ct =getContentPane( )5


getContentPane( method returns a

d.setSize(300,300); This creates a container object ct to add swing components into it. The
container object. It is defined as: Container getContentPane()
fd.setDefaul1CloseOperation(JFrame.EXIT_ON_CLOSE);

fd.BetVisibleftrue); JLabeljl =new JLabel("Swing has pluggable look and feel)


look and feel".
creates jl as JLabel object with text as "Swing has pluggable
Advanced Java Programming (MSETE 2-6 Swings
ct.arddGl; Advanced Java Frogramming (MSBTE) 2-7 Bwngs

Program 2.5.2 : Wrto a program to demonstrate a swing component lIn JApplet using web browser or appiet viewer
adds jl into container ct.

import javax.awing
JFrameDemo fd= new JFrameDemol) irmport java.awt.";
creates fd as object of user defined JFrame class.

public class JAppletDemo extenda JApplet


fdsetTitle("Demonstrating Swing");
sets title for frame. This method is defined as : void setTitle(String title)
public void sturt()
fdsetSize300,300):
sets size for frame in numbers of pixels. This method is defined as : void setSize(int width, int height) Container et = getContentPane( );

fdsetDefauliCloseOperation) window. We have to


JLabeljl = new JLabel('Demonsirating »wing components in JApplet:

closed by closing that


default ciose operation for frame. An AWT Frame cannot be
sets ct.addg);
close a JFrame window by using this
use vwindow events to close it. But here in JFrame w e can directly
additionally
operation)
mehthod. This method is define a s : void setDefaultCloseOperation (int
of WindowConstants interface declared in javax.swing
constants
This ciose operation is specified by three static
their actions. They are :
reflects
this is implemented by JFrame class. Their name
and
Step 1:CallJava program
1 F r o m e . EXIT_ ON_ CLOSE Let's call Program 2.5.2 JAppletDemo.java

2 Frame. HIDE_ ON_ CLoSE Step2:Compiled and execute


Hence compiie
and executed in the same way as we did for AWT applet programs.
JApplet program are compiled
3. JFrame. DO_ NOTHING ON_ CLOSE Ihe statement program a5
to make it
visible.
it true,
Ey detauit a frame is not visible; we have to call this meth od and apply
javac JAppletDerno.jaya
fdsetVisibie( trueji Step 3 : Run program

method is defined as
file with <applet> tag as
makes a frame window visible. This Run this Program 2.5.2, create html

voidsetVisiblelbolean vinibility) class Container. There is no


html
only to use

Program 25.1 we imported joava.awt package


Strictiy remember that, in

2.5.1
<hody
in Progran width="400" height="400"></applet>
Gther concern of inmporing jova.at package applet code="JAppletDemo.class"

2.5.2 JApplet /body


is the JAppiet. Swing
based JApplet is
uses the swing components
The second type cf application that commonly and create Container object
to add S/html>
instead of Applet
need to estend iApplet
same as AWT based Appilet. imply we and hence the life cycle of JApplet is same as the
life cycie of
Step4: Call html program and
run

e n e n d s AvT Applet
suing JApplet
as
this using appletviewer
components into it A
achieved in sring': JAppiet. Lets call rogram as one.html
and run

functionalities found in AWT Applet is


Applet and ali the of Container 5
various panes. Hence object
the J4pgiet is also a top-levei window and contains
appletviewer one.html
As Gescribed e a r i e r

add conponents into it


required to
Advanced Java Programming (MSBITE) 2-8 SWIng
Step 5:Output
Advanced Java Programming(MSBTE)
2.5.4 JLabel
Applet Viewer japplet demo.class
Applet The instance of ILabel class creates labels, used to provide instructions and information. This class has folilowing
overloaded constructors

Label(lmagelcon obj)
2. JLabel(String text)
3. JLabel(String text, Imagelcon obj, int alignment)

Here first constructor assigns specified icon, second constructor assigns specified text for the label. nird

constructor assigns alignment. This lignment is provided by LEFT, RIGHT, CENTER, LEADING
text, image and
These constants are defined in the SwingConstants interface with many others used by swing components.
or
TRAILING
D e r m o n s t a u n g s n n g c o m p o n e r i i s in JAppier

The JLabel class provides following methods to handle text and icons associated with it.

void setlcon(imagelcon obj)


Imagelcon getlcon()
3. void setText(String text)
String getTextf)
The Program 2.5.3 illustrates how to create and display a label containing both
an
a
icon and string. The appet
begins by getting its content pane. Next, an Imagelcon object is created for the file india git. This is used as the second
Applet started
for the JLabel constructor the label's text and the
argument to the Jlabel constructor. The first and last arguments are
we did earlier.
w e can also apply this <applet> tag, directly in java program; like alignment. Finally, the lable is added to the content pane.

Swing's applets use the same four lifecycle methods: init( ), start( ), paint( ), stop()
and destroy(). Of course, we label containing iecon and a string.
in Swing than Program 2.5.3: Write a program to create and display a
need to override only those methods that are by our applet.
needed Painting is accomplished differently it is

in the AWT, and a Swing applet will not normally override the paint( ) method. import javax.swing.
import java.awt.*;
2.5.3 Imagelcon
he
to any image supporting component. Imagelcon
USing an Imagelcon is the easiest way of applying an image
classes that supports providing image by applying applet code="JLabelDemo" width=300 height=300>
implements Icon interface provided by swing. There are many swing
imagelcon object as argument. There are several ways to provide an image, including reading it from file, downloading

constructors are:
S/applet>
from a URL or invoking from local system. The mo
commonly used Imagelcon
1. imagelcon(String filen_ ame)

2. imagelconfURL url) public class JLabelDemo extends JApplet


First constructor obtains the image from specified file name and second constructor downloads the image from
specified url. public void start( )

The imagelcon class defines three methods that are actually declared in Icon interface. They are:
Container ct = getContentPane( ); gettingconten pane
int getlconHeight[)
Imagelcon iil = new Imagelconf"india.gif): iicreaing an icon. Place india.git in
loc al r t
2. Int geticon Widthf)
JLabel jll = new JLabel("lndia".il.JLabel.CENTER): /creating JLabel insiance

3. void paintlcon/Component comp, Graphics g, int x, int y) ading it to container


ct.addGll);
The first method returns the hejght of the icon in pixels. Second method
Third method paints the icon at position x, y on the graphics context g
returns the width of the icon in
pixels

Knowledge
UDIatons
Advanced Java Programming (MSBTE
2-10 Swing Swings
Advanced Java Programming (MSBTE) 2-11
Output oO
SAppletViewen label,demo.class Output:
Appint
Applet Viewier tedfied denmo
Applet
You can ype here

tndna

Applet started

2.5.5 JTextField
TextField is the most simplest and widest used swing component. The JTextField allows to edit one line of text used
as input component for application.The JTextField is derived from JTextComponent class. Following are some of the

overloaded constructors of JTextField. Applet started

1. TextField)
2. JTextField|String text) 2.5.6 JTextArea
multi-line. The AWT's TextArea
3. TextFieldfint max_ chars) JTextArealTextArea is a derived class of JTextComponent thatdisplays plain text in
JTextArea can be placed inside a
JScroll Pane.
scrolling. But a
4.
TextField String text, int max chars) deals with scrolling but JTextArea doesn't manage

Here text is the string that is to be initialized and max_char is maximum capacity of characters. If first constructor is
Following are the constructors of JTextArea.
used then textfield initially appears empty.
1. JTextAreal
Program 2.5.4: Write a program to demonstrate JTextFleld in JApplet by using start( ) method which ls
overrldden and JTextField object is added in content pane. 2. TextArea (String text)
3. JTextArealint rows, int columns)
mport javAX.S Wing. "; . JTextAreo(String text, Int rows, int columns)
mport java.awt."; JTextArea(Document doc)
5.
int columns)
6. JTextArea(Document doc, String text, int rows,
JTextArea
with default settings. Second constructor creates a
creates a new empty JTextArea
First constructor
JTextArea with specified numbers of rows and
constructor creates a new empty
applet code="TTestFieldDerno" width =300 heigh=300> initialized with specified text. Third
creates a
JTextArea with specified Document model. Fifth constructor

Fourth creates a new empty


slupplet> columns.

JTextArea
constructor

which is initialized with specified text and rows & columns, in specified document model.
new

All the methods of AWT's TextArea ls also applicable to JTextArea.


public class JTextFieldiDemo extends JApplet
demonstrate the use of JTextArea.
Program 2.5.5: Wrlte a program to

public void start() import java.awt. ";

import javax.swing.";
Container ct = getContentPanel );
getung content pane class JTextAreaDemo extends JFrame
ctsetlayout(ew Flowlayout( ); scting flow layout.
JTextField jtfl new JTextField("You
=
can
type here",15); lereating textfield obect. JTextAreu areu;
cLaddgjufl); adding to eontent pane JFrame f;

publie JTextAreaDemo()
Advanced Java Programming (MSBTE) 2-12 Sw
SWIg
Container ct = getContentPane( );
Advanced Java Programming (MSBTE) 2-13 Swin
ct.setLayout(new FlowLayout( )); Program 2.5.6: Write a program to creates a combo box Into the frame and display country lilst Into it.

area=new JTextArea("This is textarea. In Without scrollbars.",20,20); import java.awt.";

area.setBounds(10,30,300,300); import javax.swing.*


ct.add(area); public class JComboBoxDemo extends JFrame
public static void maun(String ar[ ])
public JComboBoxDemo()

JTextAreaDemo fr =
new JTextAreaDemo(); Container ct = getContentPane();

fr.setSize(400,400); ct.setlayout(mull);
fr.setTitle("Demonstrating JTextArea"); / Creating combo box

fr.setVisible (true); JLabeljl = new JLabel('Select Country:);

JComboBoxje = new JComboBox( );

jc.addltem("France");
Output:
jc.addltem('Germany")
Demonstrating JTextArea je.addltem("taly');
This is textarea.
Without scrolbars. je.addltem('Japan");
l/adding combo box to content pane

ct.addg);
ct.addgc);
i/aligning components
jl.setBounds(30,50,100,30);
je.setBounds(150.50,100,30)

public static void main(String ar[ })

2.5.7 JComboxBox JComboBoxDemofrl new JComboBoxDemo();


Swing provides JComboBox class that createsa combo box. The frl.setTitle('Demonstrating combo box')5
combo box is combination of text field and a
down list. By default it shows a
drop-down list box that allows user to select one item but user can drop-
into the text filed. Following are two overloaded also type his selection frl.setsize(300,400);
constructors of JComboBox class.
1.
ComboBox() frl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
2 ComboBox(Vector obi) frl.setVisible(true);
First constructor creates an empty combo box and second constructor fills vector
can be added
manually into the combo box by
items into the combo box. Item>
using additem() method, it is defined as:
void addltem(Object ob)
ediase
2-14
Advanced Java Programming (MSBTE)
Swin
Output Advanced Java Programning (MSBTE) 2-15 Swing
Demonstrating combobax
<applet code="JButtonDemo" height="200" width="300">

/applet>
Select Country France

public class JBultonDemo extends JApplet

public void start()


2.6 SwingButtons
Swing provides four types of buttons derived from AbstractButton dlass. They
Container ct= getContentPane();
are JButton, JToggleButton
JRadioButton and JRadioButton. Here we will discuss about these abstract button classes. ct.setLayout(new FlowLayout( );
Imagelcon iil = new Imagelcon('india.gif);
2.6.1 JButton
JButton jbtl = new JButton("India".iil):
The JButton is very much different from AWT Button in many respects.
ct.addjbtl):
Following are the overloaded constructors of JButton class :
. JButton(String label)
2. JButtonflmagelcon obj)
3. JButton(String label, Imagelcon obi) Output
JButton class has following methods to deal with its label and icon
Applet Viever jbutton demo
1. void setlabel(tring label) Applet

.
String getlabe!)
3. vold setlconlmagelcon ob)
4. Imagelcon geticon() nia

The base class AbstractButton also contains methods that allows to control behavior of buttons.
some us These
methods are

1. vold setDisablediconflcon obl)

2. vold setPressediconficon obl)D


Applet started.
3. vold setSelectediconficon ob)

void setRolloverlconflcon obl)


2.6.2 JCheckBox
Here purpose of each method is indiated
by its name. All the AbstractButtons invokes many events.
of
two stated button. it is swing version
Program 2.6.1: Wrlte program that demonstrates JButton with lcon and label on It. JCheckBox is the immediate derived class of JToggleButton which provides
AWT Checkbox which provides the facility to insert images also.
import javax.awing of the overloaded constructors of JcheckBox:
Following are some

import java.aw. JCheckBox(lmagelcon obj


1.

2. JCheckBoxfimagelcon obj, boolean state)


Advanced Java Programming (MSBTE) 2-16
3. JCheckBox(String text) SWin
4. JCheckBox(String text, boolean state) Advanced Java Programming (MSBTE) 2-17
Swin9
. JCheckBox(String text, Imagelcon obj) ch2.setBounds(150,50,100,30);
JCheckBox(String text, Imagelcon obj, boolean state) ch3.setBounds(30,100,100,30);
Here obj is the object of ch4.setBounds(150,100,100.30);
Imaglcon and text is string that appears
the on checkbox and state specifies
state. If state is true then checkbox initial choe
initially appears selected otherwise not. checke
To handle different events public static void main(String arl })
on JCheck80x we have following
JCheckBox methods:
1VoidsetText(String tert) JCheckBoxDemofrl = new JCheckBoxDemo( );
2 String getText()
3. Void seticon(Imagelcon obj)
frlseTitle("'Demonstrating JCheckBox);
frl.setSize(300,300);
Imogelcongetlcon( frlsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Void setSelectedfboolean state)
frl.setVisible(true);
6.
booleanisSelected()
Here, setselected( ) is to
change the state of
invoking JCheckBox object. It returns true if checkbox
otherwise returns false. is checked
Output:
Program 26.2: Write a program that
demonstrate a
toggle button. Demonitating JCheckeoxe |
import javar swing"
import java.awt" Option 1 Option 2
public elass JCheckBoxDemo extends JFrame
Optian 3
Option 4

publie JCheckBoxDemo)

Container et =
getConientPane( );
2.6.3 JRadioButton
eLsetlayout(nully;
stated button. It is swing version

JCheckBox chl JRadioButton is the immediate derived class of JToggleButton which provides two
=
new
JCheck Box('Option l',true); of AWT Radio button which provides the facility to insert images
also.
JCheckBox ch2 =
new
JCheckBox( Option 2); Following are some of the overloaded
constructors of JRadioButton:
JCheckBox ch3 =
new
JCheckBox(Option 3"); JRadioButton(lmagelcon ob)
1.
JCheckBox ch4 =
new
JCheckBox("Option 4',true); 2. JRadioButton(tmagelcon obj, boolean state)

ctadd/chl) 3. JRadioButton(String text)

ctadd(ch2); 4. JRadioButton(String text, boolean state)

et.add/ch3); 5. JRadioButton(String text, Imagelcon obl)

JRadioButton(String text, Imagelcon obj, boolean state)


ct.add(ch4) b.

chl.setBounds(30.50,100,30);
ch Knowled
Swings

Programming (MSBTE)
2-18 Sin Advanced Java Programming (MSBTE)
2-19
and state
dvanced Java

and text is the string


that appears on
radio button
specities in
sper

i/aligning components

Here obj is the object of Imaglcon selected otherwise


not.
button initially appears rbl.setBounds(30,50,100,30);
is true
then radio
ed state. If state button can be checked from aa group
of the radio
into a group.
Hence, only one rb2.setBounds(150,50,100,30):

Radio buttons must be configured selected radio button will get deselected. For
automatically
previously th rb3.setBounds(30,100,100,30);
radio button then class to add radio k
time.If user selects a
default constructor. Use add( ) method
of Button Group butt rb4.setBounds(150,100,1 00.30):
class with
te object of ButtonGroup
rb5.setBounds(270,100,100,30):

ects into a group.


void add(JRadioButton ob
/lcrating button groups
button and also add then into a group.
2.6.3 Write a program by using radio
bgl new ButtonGroup():
:
gram ButtonGroup
=

ButtonGroup bg2 = new ButtonGroup( )


port java.awt.";

port javax.swing." bgl.addirbl);


bgl.addtb2);
bg2.add(rb3),
width="400"> bg2.addcb4),
applet code="JRadioßuttonDemo height="200"
bg2.addtb5)
lapplet>

Output:
ublicclass JRadioButtonDemo extends JApplet Applet Viewer jradiobutton_ demo
Appiet

public void start()

Male Female

Container ct= getContentPane( ); O tternet Expl Mozill Firefax


GOOgle Chro

ctsetlayoutfmul);
icreating radio buttons

JRadioButton rbl = new JRadioBullon('Male");


Applet stared

JRadioBulon rh2 = new JRadioButtonl"'Female");


JRadioButton th3 = new JRadioButton("Internet Explorer );
2.7 Advanced Swing Components
JRadioButton rhd= new JRadioButton "Moill Firefox): advanced components that were not provide in AWT,; such as: TabbedPane,
Additionally, swing also provides
some
Let
Swing based
us
in applications.
has separate usage
JToolTip. These component
JRadioBuiion rbs = new JRadioButton 'Google Chrome"'); JTree, JScroll Pane, JTable, JProgressBar,
discuss these swing components in detal.

2.7.1 JTabbedPane
/adding radio buttons to conteni pane and a panel as group
each containing a titie
JTabbedPane is a which appears as a group of muitiple tabs,
component The main
ctLaddirbl) of components. When user selects a tab, its
contents becomes visible and
user can interact it's with the contents.

related options.
ot.addrh2); purpose of tabbed panes
is to provide configuration

etaddlth3); tools menu Folder options)


(For example windows explorer
it's default constructor and add different tabs under it using addTabi
ctaddirhA): We create the object of TabbedPaneusing
method. This method is defined as
taddlrh5)
voidaddTab(String tile, Component oby)
Tch Kesusd
t
2-20
Advanced Java Programming (MSBTE) SwIn
that should be added to ically, aJpanel
thetab. Typically
Advanced Java Programming (MSBTE) 2-21
the tab, and obj is the component
Here, title is the title for
subclass of it is added. JButton jbt3 = new JButton('Str);

tabbed pane is as follows: JButton jbt4 new JButton("Pineapple");


The procedure to use a

it.
classes with components in
1. define required numbers of panel addgbtl);
createJTabbedPane object. addgbi2);
related panel object.
. call its addTab() method with a
titleand add gjb:3);

the container of JApplet or JFrame.


add the tabbed pane into addgbt4);

with the help of Jpanel.


Program 2.7.1: Wrtte a program by creating a tabbed pane

import java.awt. extends JPanel


class pnl3
mport javax.swing.

applet code="JTabDemo" height="200" width="400">


public pnl30
S/applet JComboBoxjcb =
new JComboBox( );
jcb.addltem"'Circle");
class pnll extends JPanel jcb.addltem("'Oval");

jcb.addltern("Rectangle");

publie pnl10 jcb.addltem('Square");

addgcb);
JCheckBox jchl =
new
JCheckBox("Red")
JCheckBox job2 =
new
JCheckBox("Blue")
JCheckBox jcb3= new JCheckBox('Green'");

JCheckBox job4 new JCheckBox("Yellow'); public class JTabDemo extends JApplet


addjebl);
public void start( )
nddGeb2);
add(gjeb3); Container ct =
gtContentP'ane( );
JTabbedPane jip = new JTabbedPane( );
addgjcb4);
jtp.addTab("'Colors",new pnll( ):
jtp.add'T'ab("Flavours",new pnl2( ):

jip.addT'ab('Shapes",new pl3( )):


elass pul2 extends JPanel
ct.add(gtpP);

public pnl20

The Program 2.7.1 contains a tabbed pane with three tabs in it

JButton jbt l =
new
JButton("Chocolate"); Colors: having four checkboxes with color options.

JButton jbi2 new JButton("Vanila"):


aand
ach Knouled
2-22 Swings
(MSBTE) 2-23
Aavanoed Java Programming Advanced Java Programming
(MSBTE)
buttons with flavoroptions.
Flavours: having four 1. JScolIPane(Component obj)
with shape options. JScolPaneflnt vertlcal, Iint horizontal)
combobox

Shapes having a
JScollPane(Component obj, int vertical, int horizontal) the int
3. and horizontol are

which is required to be placed in scroll pane. vertical constants


Output Here, obj ls the component object ScrollPaneConstants interface. These
type of horizontal and vertical scrollbar defined in
Applet Viever tab.demo that defines
constants
Appet re
Colors Favours Shapes HORIZONTALSCROLLBARALWAYS
Yollow HORIZONTAL_SCROLLBARAS_ NEEDED
Red Blue Green
2.
3. VERTICAL SCROLLBAR ALWAYS
VERTICAL SCROLLBAR_AS NEEDED
4.
Their names specifies their appearance.

scroll pane controlling a text area.


that demonstrates a
Write a program
Program 2.7.2:
mport java.awt. ";
Applet started
import javax.swing.";

Appiet iewer jtabdemo


Appiet width=300 height=250>
Sapplet code="JScrolPaneDemo
Calors RavDurs Shapes
S/applet>
Chocolate Vanila Str Pineapple

extends JApplet
public class JScrollPaneDemo

public void start()

Applet started Container ct =getContentPane( );


with horizontal and n t
Strings"This is text arean" displayed in a scroll paneyi + appears
Applet Viewer jtab demo "vertical scrollbar";
Appiet
I/scroll pane constants.
Colors Flvours Shapes int h = ScrollPane Constants. FHORIZONTAL_SCROLLBAR_ALWAYS:
Circle int v= ScrollPaneConstants, VERTICAL_SCROLLBAR_ALWAYS:
Circle
|Oval
Rectanple /lcreating text area.
Square
JTextAreajt = new JTextArea(s);

Applel starled iereating scroll pane ad applying text area with serollbas
JScrollPanesp = new JScrollPanet,v.hy;

2.7.2 JScrolIPane

IScrollPane is the class that iladding scroll pane to content pane


provides a rectangular scrollable area In which a component can be viewed. Horizonal
and/or vertical scrollbar may be provided if required. Some of its ct.addsp):
overloaded constructors are:

Tec PupitEafiBR"
Kaseladgi 'ahareslsdgi
APpie Viewer jscroipaneen
Appiet
This IS text area
applet code="JTrecDenio" width=400 height=200>
pane
displayed in a scrol and /applet
horzontal
appears with
erical scrollbar

public elass JTreeDemo extends JApplet

publie void start( )

Container ct = getContentPane( );
Get content pane

ADDlet started

ct.setLayout(new Borderlayout( )): / Set layout manager


2.7.3 JTree
A JTree is an expandable and collapsible component containing sub-trees to display. Some of the JTree constructon // Create top node of tree
are following
DefaultMutableTree Node root= new DefaultMutableTreeNodef"Options"):
1. Tree(Hashtoble obj)
2 TreefObject obil ) 1 Create subtree of "A"
3. TreefTreeNode obi)
4. TreefVector obi) DefaultMutable TreeNode a =
new DefaultMutableTreeNode("A"):

Here, each obj is object of respective components.


root.add(a);:
A JTree generates event when it gets expanded or collapsed. The TreeNode interface declares methods that obtain
DefaultMutableTreeNode al = new
DefaultMutableTree Node("Al"):
information about a tree node. a.add(al);
For Example : It is possible to obtain a reference to the parent node or anenumeration of the child nodes. The DefaullMutableTreeNode a2 = new DefaultMutableTreeNode "A2");
MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the a.add(a2):
parent node. The DefaultMutable TreeNode class implements the MutableTreeNode interface. It represents a node in a
tree. One of its constructors is shown here:
i Create subtree of "B"
DefaultMutableTree Node(Object ob) DefaultMutableTreeNode b = new DefaultMutable'TreeNode("'B");

Here, obj is the object to be enclosed in this tree node. The new tree node doesn't have aparent or children.To
create a hierarchy of tree nodes, the add() method of DefaultMutableTreeNode can be used. Its signature is shown here:
root.add(b);:
DefaultMutableTreeNode bi = new DefaultMutableTreeNode("B1"):
void add(MutableTreeNodechild b.addbl):
Here, child is a mutable tree node that is to be added as a child to the current node.
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");:
Program 2.7.3 : Write a program that demonstrate creatlon of tree.
b.addh2);
mport java.awt. " DefaultMutableTreelNode b3 =
new
DefaultMutable'Tree Node("B3");
import ja vax.swing." b.add(b3);
import javax.awing.tree. ;
/Create tree
JTreetree new JTree(root):
Tech NKneleds
PUDITCatiou
2-26
Advanced Java Prograrmming (MSBTE)
Add tree to a scroll pune Advanced Java Programming (MSETE) 2-27 S
SCROLLBAR_AS_NEEDED;
public class JTableDemo extends JApplet
int y=
Scroll PaneConstants.VERTICAL
SCROLLBAR_AS_NEEDED;
int h =
SerollPaneConstants. HORIZONTAL
JScrollPane jsp =
new JScrollPane(tree, v. hy: public void alart()
i Add scroll pane to the conlent pane
Container ct = getContentPane():
ct.addjsp, Borderlayout.CENTER): e l conten! pane

ct.setLayout(new Borderlayoutí }): Set layout manager

Output:
final String[] colHeads =
{"Roll". "Name". "city". "phone"}: /
Initialize column headings
Applet Viewer jtreedemo
Appet / Initialize data

Options final Object[ ][] data = {

A { "r, "Amie", "Ahmedabad", "559847" }.


DA2
C "2"."Ketan","Rajkot","756655"}.
"3", "Vivek". "Junagadh"."563458"
83 { "4", "Mahendra". "Rajkot". "734592"}.
("s", "Ankita", "Surat", "123733" },
Applet stated ' 6 , "Jayesh", "Baroda', "565614" ),

2.7.4 JTable {"7", "Rajshree", "Jamnagar". "567221" .

thecursor on column boundaries to "8"."Suresh","Surat","674142" },


and columns of data. You can drag
A JTable is a component that displays rows

constructors is shown as followsS:


resize columns. You can also draga column to a newposition. One of its 9", "Hiren","Rajkot","902375"}
JTable(Objectdatal [ 1, Object collieads ])
and colHeads is a one-dimensional aray
the information to be presented,
Here, data is a two-dimensional array of
with the column headings. Create the table
JTable table = new JTabletdata, colHeads):
Here are steps to create a table in scroll pane :

create Table object with data and column titles. i/ Add table to a scroll pane
table into it.
create ScrollPane object and provide the VERTICAL_SCROLLBAR_AS_NEEDED,
int v ScrollPaneConstants.
add the scroll pane into the content pane.
3. ScroliPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED

inth
=

Program 2.7.4: Write a program to


create a table using an appletvlewer. = JSerollPaue(table. v, h):
JScrollPanejsp new

the content a n e
/ Add seroll pane to

ctaddisp. BorderLayout.CENTER);
importjava.awt.";
import javax.swing"

Sapplet code="TableDemo" width=400 height=200>

applet> TechKaoulb
PUbIICaT
(MSBC
28 Sin (MS8TE
Advarnced
Java Programming Advanced Java Programming
getLontentPane :
Container ct
=

Output
AppietVieenabie dem jb=new.JProgressBar(0.2000):
phone
AGDE Name
559347
Ro ng030s
Rajko
756655 jb.setBounds(40,40,200,30;

Ketan 563458
Vivek Junag30 734592
jb.setValue(0);
Rao
Maneno 123733
Anita arooo
565814 jb.setStringPaintedtnue);
Jayesn 567221
Rajshree 674142
Suresh 902375 ct.addb):
Hiren

this.setSize(400,400):

ct.setLayoutínew FlowLayoutt ):
Dpiet staneo

2.7.5 JProgreesBar public void iterate()


the
shows the progress of a task. We can say that it shows percentage
JProgress Bar is a component that graphically
its data model, and an important property
used by
task. JProgress Bar uses a Bounde dRange Model
as
of completion of
progressbar is its value. whilefi< =2000)

Following are the overloaded constructors of JprogressBar

1. IProgressBarf)
jb.setValueti);
ProgressBar(BoundedRangeModel model
i=i+20;
JProgressbarlint orient)
ProgressBarfint min, int max) try

5. IProgressBarfint orient, Int min, int max)


First constructor creates a horizontal Progress-bar border but no processing string Second constructor creates a
horizontal JProgressBar with specified model to hold the Progress-bar's data. Third constructor creates a new
new Thread.sleep(150)
JProgressBar creates IProgressBar with specified orientation. This orientation can be specified by Swing Constant
VERTICAL new horizontal JProgressBar with specified
and
or
Swing
Fifth
Constants HORIZONTAL. Fourth constructor creates a min
max vaiue. constructor creates a new JProgress8ar with specified orientation and minimum-maximum value. catch(Exception e)
Program 2.7.5: Write program to demonstrate
a
progress-bar 8howing progress value in //end of while
setvalue() method.
a
percen tages by using

nport javax. swing."


public statie void main(String aul })
mport java.awt. ";
public elass MyProgress extends JFraie
MyProgress m=new MyProgress( );

JProgressBar j m.setTitle('Progress-bar Demo"):


int i=0,um =; m.setVisible(true);
puhlie My Progress m.iterate( );
SH
2-31
Programming (MS8TE)
(MSBTE Advanced Java
Acvanced Java Programmng Area");
tsetToolTipTextý'this is
a text
The setValue( ) metha.

percentages.

value in
Output progress-Dar
showing
progress P.addtl):

snow a
275
ine Program
f.addp
of JProgressb2r. Progress-bar Demo
set tne value
LsetSize(300, 300):

fshow):
31

Output
ox
frame

this is a tet Area


2.7.6 JToolTip
that shows a temporary pop-up message
when the mouse pointer stays on
Tooiup
i5 very importarnt component We can add toolti;
cOmpanent Tnis pop-up message can be a short description or labelled information of any component.
tet to almost all the componen ts of Java Swing
This method is defined as
To 2dd
tool ip to a component cbject, we have set Tool Tip Text[ ).
void efToolTipText(String text)
is displayed.
the of that component a popup appears and text
When the cursor enters boundary
textarea.
Program 2.7.6: Write a program that demonstrates the
use
of tooltip on a

2.7.7 JSIider
import javax.swing.event.":
JSlider is a component that allows the user to select a value by moving the knob. The knob is always positioned at
LTaort java.awt. ";
the points that match the integer values within the specified interval.
nport ja vax ing.".
Following are the commonly used constructors ofJslider:
1. JSlider()
class JTrolTiy,Deno etend: JFrame
2. JSlider(BoundedRangeModel model)

3. JSlider(int orient)
Latic JFrane f.
4. JSlider(int min, int max)
stat JTeatAira t:
5. Slider(int min, int max, int value)
publie stalir yoid mainftringl args) 5. JSliderfint orient, int min, int max, int value)

First constructor
f= new Jf rainet
trane ) creates a horizontal slider with range 0 to 100. Second constructor creates a new horizontai JSlider
with specified mode. Third constructor creates a new ISlider
creates JSlider with specified orientation with the
JToalTipenu rx Jfomllipitetmof ). to 100 and intial value 50. Fourth
range of O0
constructor creates a new horizontal Slider with
JPanel p = new JPaneli specified min and max vaBue Fifth
constructor creates a new JSlider with
specified minimum-maximum and initial value. Sixth constructor
creates a
t new JTextArea(20, 20): horizontal slider with specified orientation,
maximum-minimum value and initial vaBue.

TechKnvuledgi
2-32
Java Programming (MSBTE)
Advanced
The number of values
between marks isis controlleg
the tick marks
and minor tick marks.
Advanced Java Programming(MSBTE) 2-30 Swings
The slider can show major
and the painting of
tick marks is controlledby serp
setMojorTrickSpacingl) and setMinorTickspacingl)
methods
PointTick Output:
method.

Some of the commonly used methods of JSlider class are: Demonstrating 1Sider
.publile voidsetMinorTickspacingfint n)
2. public vold setMajorTickspacinglint n)
public void setPointTicks(boolean b) 2.7.8 JDialog

public vold setPaintLobelstbooleon b) The JDialog is used for creating a dialog window. This class extends AWTs
Dialog class and can be used to create aty
type of custom dialog boxes with the use of JOption Pane.
public void setPaint Tracks(boolean b)

of JSlider. Program 2.7.8: Write a program that demonstrates the creation of dialog-box using JDialog
Program 2.7.7: Write a program that demonstrates the use

import java.awt.";
import javax.swing" import java.awt.event.":
import java.awt.";
import javax.swing.";

public elass JSliderDemo extends JFrame


public class JDialogDemo extends JDialog implements ActionListener

public JSliderDemo() public JDialogDemo{JFrame parent, String title, String message)

Container ct = geiContentPane(O: super(parent, title, true);


JSlider slider if(parent!= null)
=
new
JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
Dimension parent>ize parent.getsize( );
=

panel.add(slider);
ct.addipanel); Point p parentgetLocation ):
setLocation(p.x + parentSize. wid1h 4. p.y +parentSize.height / 4);

public static void


main(String aul l}
JPanel message Pane =
new JPanel(0:
messagePane.add(new JLabel(message):
JSliderDemo frame=new JSliderDemof ): getContentPane( ).add(message Pane):
Irame.pack( ); JPanel button Pane =
new JPanel( );

frame.setTitle("Demonstrating JSlider"); JBulton button =


new
JBulton OK");
trame.setVisibleftrue); buttonPane.add(button):
button.add.ActionListener(this);
getContentPane( 1.addbuttonPane, BorderLayaut.SOUTH);
setDefaultCloseDperation(DISPOSE_ON_CLOSE)
pack)
Advanced Java FQidIliun Ot

setlisiblettrue)
Advancod Java Programming (MSBTE) 2-35 Swing
In MVC architecture

sclionPerfur1medtActionEvent e) (0) Model


Dublie void
It defines the state information i.e. the events and its graphical change when an event occurs on a component

For exampie imagine the graphical movement that happens when a JButton is pressed. It looks like pressed
setVisibleifalse: downwards.

dispose( () View

It defines how that component is displayed on the screen. Including the change in state affected by the events
performed on it.
public slaic void main(String arl }
(li) Controller

JDialogDemo dlg = new JDialogDemo(new JFramet ), "Demonstrating Dialog', "message"): It controls now the component will react to user. For example, when a checkbox is checked or unchecked it
changes its state and appearance.

However, this distributed architecture makes it pluggable look and feel; but practically speaking, this separation
of view and controller is not beneficial for swing components. Hence the newer versions of Java have started
using a new design pattern called UI which combines View and Controller os a single unit and merge it with
Output Model. This new approach of swing is called as Model-Delegate architecture or Separable Model Architecture

Demonstrating Dialog According to this new Model-Delegate architecture, every swing component contains two objects. One
represents Model and second represents the Ul delegate. Remember that, our program will never directly
messagee
interact with these Ul delegate, but instead all swing components internally cooperate with the it's related
UI delegate. For example, the JTextField internally interacts with JTextFieldUl without notification to developers.

OK
Review Questions
2.8 MVC Architecture ?
a.1 Differentiate between AWT and Swing components. 4 Marks)
The MVC architecture is the most adopted component architecture that effectively contains: Model -
View
Controller. Any component has three major phases: a.2 Explain how Frame and JFrame differs. List all the methods of JFrame. (3 Marks)

2 Marks)
The information/properties associated with that
component a.3 What is main difference between TextField and JTextField?

2. The way that the component looks when submitted on the screen. a.4 Write a program to demonstrate use of JComboBox. (4 Marks)

3. The way that the components reacts to user. (5 Marks)


a.5 List and explain constructors of JRadioButton.

There are many other architectures used to implement a component, and all contains above three phases. But the a.6 Explain the steps to create JTabbedPane in swing. Also write one example to demonstrate it. 5 Marks)
MVC is the most adopted component architecture
a.7 Write a program to demonstrate JTree component in swing. (4 Marks)
The MVC architecture is successful because each component
corresponds to all phases. Ih MVC architecture, the
model represents the information/properties associated with the (3 Marks)
component, the view represents the way that a.8 Explain the constructors of JProgressBar.
component is displayed, and the controller represents how the component reacts to user. For
example, in case of a and show the of setToolTipText( ) method. (2 Marks)
Listbox, the model controls the properties containing collection of items of Listbox, the view controls how a.9 Explain use
it is displayed
and which item is initially kept as selected, the controller controls
the reactions of Listbox on user clicks.
MVC design pattern is the key of success of swing Chapter Ends.
components that provides pluggable look and feel. The MVC
architecture is successful because each piece of the design handles an individual
phase of component.

TechKneuld
BIEtions

You might also like