Ajp Chapter 2
Ajp Chapter 2
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.
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
(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,
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
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
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
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
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
import javax.swing.";
Swing has pluggable look and feel
import java.awt.";
class JFrameDemo extends JFrame
publie JFrameDemo()
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
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);
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.
method is defined as
file with <applet> tag as
makes a frame window visible. This Run this Program 2.5.2, create html
2.5.1
<hody
in Progran width="400" height="400"></applet>
Gther concern of inmporing jova.at package applet code="JAppletDemo.class"
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
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.
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)
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
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
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
JTextArea
constructor
which is initialized with specified text and rows & columns, in specified document model.
new
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.
JTextAreaDemo fr =
new JTextAreaDemo(); Container ct = getContentPane();
fr.setSize(400,400); ct.setlayout(mull);
fr.setTitle("Demonstrating JTextArea"); / Creating combo box
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)
/applet>
Select Country France
.
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
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)
chl.setBounds(30.50,100,30);
ch Knowled
Swings
Programming (MSBTE)
2-18 Sin Advanced Java Programming (MSBTE)
2-19
and state
dvanced Java
i/aligning components
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):
Output:
ublicclass JRadioButtonDemo extends JApplet Applet Viewer jradiobutton_ demo
Appiet
Male Female
ctsetlayoutfmul);
icreating radio buttons
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
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);
jcb.addltern("Rectangle");
addgcb);
JCheckBox jchl =
new
JCheckBox("Red")
JCheckBox job2 =
new
JCheckBox("Blue")
JCheckBox jcb3= new JCheckBox('Green'");
public pnl20
JButton jbt l =
new
JButton("Chocolate"); Colors: having four checkboxes with color options.
Shapes having a
JScollPane(Component obj, int vertical, int horizontal) the int
3. and horizontol are
extends JApplet
public class JScrollPaneDemo
Applel starled iereating scroll pane ad applying text area with serollbas
JScrollPanesp = new JScrollPanet,v.hy;
2.7.2 JScrolIPane
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
Container ct = getContentPane( );
Get content pane
ADDlet started
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
Output:
final String[] colHeads =
{"Roll". "Name". "city". "phone"}: /
Initialize column headings
Applet Viewer jtreedemo
Appet / Initialize data
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
=
the content a n e
/ Add seroll pane to
ctaddisp. BorderLayout.CENTER);
importjava.awt.";
import javax.swing"
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
1. IProgressBarf)
jb.setValueti);
ProgressBar(BoundedRangeModel model
i=i+20;
JProgressbarlint orient)
ProgressBarfint min, int max) try
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
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.";
panel.add(slider);
ct.addipanel); Point p parentgetLocation ):
setLocation(p.x + parentSize. wid1h 4. p.y +parentSize.height / 4);
setlisiblettrue)
Advancod Java Programming (MSBTE) 2-35 Swing
In MVC architecture
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)
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