Introduction To Swing
Introduction To Swing
Introduction
Swing is the set of classes that provides more powerful
and flexible components as compare to AWT
Swing provides some special additions like
Tables,Trees,ScrollPanes,TabbedPanes etc
It also provides the functionality for adding images
using ImageIcon class
Swing components are not implemented by platform
specific code,they are written in Java and thus they are
platform-independent…such elements are called as
Lightweight elements
Following are this list of Swing classes used in the
programs:
Swing Classes
AbstractButt ImageIcon JApplet JLabel
on
JButton JCheckbox JTextFiel JScrollPane
d
JList JRadioButton JTree JTable
JTabbedPan JComboBox
e
MVC Architecture
MVC stands for Model View Controller.
MVC is a software design pattern that is used for the
development of the web application
There are 3 major parts of MVC Architecture as follows:
Model:- It is bottom most level of the MVC
architecture,the major function of this layer is to maintain
the data.
View:-Another part of MVC model called view is used to
display the full data or partial data to the user.
Controller:-It controls the interaction or communication
between model and view parts.
Event
Controller
View
Model
JApplet
JApplet class is fundamental to Swing,which extends
Applet
Applets that use Swing must be subclasses of JApplet
JApplet supports various “panes”, such as the
ContentPane,the GlassPane and the RootPane
Main difference between Applet and JApplet is that when
adding a component to an instance of JApplet,do not
invoke the add() method of the applet
Instead it call add() for the Content pane of the JApplet
object
The content pane can be obtained by:
Syntax: Container getContentPane()
The add() of Container can be used to add a
component to a content pane
Syntax: void add(Comp)
Here comp is the component to be added to the
Content Pane
ImageIcon
In Swing,icons are encapsulated by the ImageIcon
class,which paints an icon from an image
It defines the following Constructors as:
ImageIcon(String FileName)
ImageIcon(URL url)
The first form uses the image in the file named
filename
The second form uses the image in the resource
identified by url
ImageIcon class supports the following methods as:
int getIconHeight()
int getIconWidth()
void paintIcon(Component comp,Graphics g,int x,int
y)
First form returns the height of icon in pixels
Second form returns the width of icon in pixels
Third form paints the icon at position x,y on the
graphics context g. Additional information can be
provided in comp
JLabel
Swing labels are instances of the JLabel class,which extends
Jcomponent
It can display text and/or an icon
It defines the constructors as:
JLabel(Icon i)
JLabel(String str)
JLabel(String str,Icon i,int align)
In above constructors,str is the text and i is used for icon
used for the label
The align can be LEFT,RIGHT,CENTER,LEADING or
TRAILING
The icon and text associated with the label can be read
and written by using following methods as:
Icon getIcon()
String getText()
void setIcon(Icon i)
void setText(String str)
In above methods I is icon and str is text
import java.awt.*;
import javax.swing.*;
/*<applet code="JLabelDemo" height=300 width=300>
</applet> */
public class JLabelDemo extends JApplet
{ public void init() {
Container c=getContentPane();
ImageIcon i=new ImageIcon("Tulips.jpg");
JLabel jl=new JLabel("AJP",i,JLabel.LEFT);
c.add(jl);
}
}
JTextField
The swing TextField is encapsulated by the
JTextComponent class,which extends the Jcomponent
JTextField allows us to edit one line of text
Constructors are:
JTextField()
JTextField(int cols)
JTextField(String str,int cols)
JTextField(String str)
Here,str is the string to be presented and cols is the
number of columns in the text field
import java.awt.*;
import javax.swing.*;
/*<applet code="JTextFDemo" height=300 width=300>
</applet> */
public class JTextFDemo extends JApplet
{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
JTextField jl=new JTextField(20);
c.add(jl);
}
}
Buttons
Swing defines the 4 types of buttons as:
JButton JCheckbox JRadioButton JToggleButton
These all are subclasses of the AbstractButton
class,which extends JComponent
AbstractButton contains many methods that allow us to
control the behavior of buttons,checkboxes and radio
buttons
For ex: we can define different icons that are displayed
for the component when it is disabled,pressed or selected
The following are the methods that control this behavior:
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 for the
different conditions like disabled,pressed,selected and
rollovered
The text associated with a button can be read and
written by following methods as:
Sting 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
Its constructors are as follows:
JButton(Icon i)
JButton(String str)
JButton(String str,Icon I)
Here, str is the String and i is the icon used with button
import java.awt.*;
import javax.swing.*;
/*<applet code="JButtonDemo" height=300 width=300>
</applet> */
public class JButtonDemo extends JApplet
{
public void init() {
Container c=getContentPane();
c.setLayout(new FlowLayout());
ImageIcon i=new ImageIcon("Tulips.jpg");
JButton jb=new JButton("CSR",i);
c.add(jb);
}
}
JCheckbox
The JCheckbox class provides the functionality of a
Checkbox which implements AbstractButton interface
Constructors are:
JCheckbox(Icon i)
JCheckbox(Icon i,Boolean state)
JCheckbox(String str)
JCheckbox(String str,Boolean state)
JCheckbox(String str,Icon i)
JCheckbox(String str,Icon i,Boolean state)
Here i is the icon for the button
The text is specifies by str
If boolean state is true then the Checkbox is initially
selected otherwise it is not
The state of Checkbox can be checked by using
following method as:
Syntax: void setSelected(Boolean state)
Here state is true if the Checkbox should be checked
import java.awt.*;
import javax.swing.*;
/*<applet code="JChkboxDemo" height=300 width=300>
</applet> */
public class JChkboxDemo extends JApplet
{
public void init() {
Container c=getContentPane();
ImageIcon i=new ImageIcon("Tulips.jpg");
JCheckBox jc=new JCheckBox("MGMT",true);
//JCheckBox jc1=new JCheckBox(“AJP",i,true);
c.add(jc);
//c.add(jc1)
}
}
JRadioButton
Radio Buttons are known as option buttons as we can select
only one option or button at a time in a given group of
options
The Radio Buttons are supported by the JRadioButton class
It is a solid implementation of AbstractButton
It supports the following construtors:
JRadioButton(Icon i)
JRadioButton(Icon I,Boolean state)
JRadioButton(String str)
JRadioButton(String str,Boolean state)
JRadioButton(String str,Icon i)
JRadioButton(String str,Icon i,Boolean state)
Here,i is the icon for the button,the text is specified by
str
If state is true,the button is initially selected..otherwise
it is not
The ButtonGroup class is used and initialized to create
a group of buttons
Default constructor of ButtonGroup is invoked for this
purpose
Elements can be added to the group of buttons by using
following method:
Syntax: void add(AbstractButton ab)
Here,ab is the reference to the button to be added to the
group
import java.awt.*;
import javax.swing.*;
/*<applet code="JRadBDemo" height=100
width=100></applet> */
public class JRadBDemo extends JApplet
{
public void init() {
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
JRadioButton jb=new JRadioButton("MGMT",true);
JRadioButton jb1=new JRadioButton("CSR",false);
JRadioButton jb2=new JRadioButton("AJP",true);
c.add(jb);
c.add(jb1);
c.add(jb2);
}
}
public class JRadBDemo extends JApplet
{ public void init() {
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
JRadioButton jb=new JRadioButton("MGMT",true);
JRadioButton jb1=new JRadioButton("CSR",false);
JRadioButton jb2=new JRadioButton("AJP",true);
c.add(jb);
c.add(jb1);
c.add(jb2);
ButtonGroup bg=new ButtonGroup();
bg.add(jb);
bg.add(jb1);
bg.add(jb2);
} }
JList
JList is a Swing component used to create list in swing
Constructors are:
JList()
JList(Object[] listData)
JList(Vector listData)
JList(ListModel dataModel)
First form constructs a JList with an empty model
Second form constructs a JList that displays the elements in
the specified array
Third form constructs a JList that displays the elements from
particular Vector
Fourth form constructs that displays the elements in
the specified non-null model
Methods used with JList are as follows:
setSelectedIndex()-selects a specified single cell from
the list
Syntax: public void setSelectedIndex(int index)
getSelectedIndex()-returns the selected index,it returns
-1 if no item is selected
Syntax: public int getSelectedIndex()
getSelectedValue()-returns first selected value or
displays null if nothing is selected
Syntax: public Object setSelectedValue()
import java.awt.*;
import javax.swing.*;
/*<applet code="JListDemo" height=100 width=100> </applet>
*/
public class JListDemo extends JApplet
{
public void init() {
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER));
String data[]={"AJP","CSR","MGMT","STG"};
JList jl=new JList(data);
c.add(jl);
}
}
JScrollPanes
A scroll pane is a component that presents a rectangular area in
which a component may be viewed. Horizontal and/or vertical
scroll bars may be provided if necessary.
Scroll panes are implemented in Swing by the JScrollPane class,
which extends JComponent. Some of its constructors are shown
here:
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Here, comp is the component to be added to the scroll pane. vsb
and hsb are int constants that define when vertical and horizontal
scroll bars for the scroll pane
These constants are defined by the ScrollPaneConstants
interface. Some examples of these constants are described as
follows:
Example:
import java.awt.*;
import javax.swing.*;
/*<applet code=JTableDemo height=200 width=200> </applet>*/
public class JTableDemo extends JApplet
{
public void init()
{
Container c=getContentPane();
c.setLayout(new BorderLayout());
final String[] colheads={"Name","City"};
final Object[][] data={{"Abc","Pune"},{"Xyz","Solapur"},
{"Pqr","Mumbai"}};
JTable jt=new JTable(data,colheads);
int
v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEED
ED;
int
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NE
EDED;
JScrollPane jsp=new JScrollPane(jt,v,h);
c.add(jsp,BorderLayout.CENTER);
} }
JTree
A tree is a component that presents a hierarchical view of data.
Trees are implemented in Swing by the JTree class, which
extends JComponent. Some of its constructors are shown here:
JTree(Hashtable ht)
JTree(Object obj[ ])
JTree(TreeNode tn)
JTree(Vector v)
The first form creates a tree in which each element of the hash
table ht is a child node.
Each element of the array obj is a child node in the second
form. The tree node tn is the root of the tree in the third form.
Finally, the last form uses the elements of vector v as child
nodes.
A JTree object generates events when a node is expanded
or collapsed.
The addTreeExpansionListener( ) and
removeTreeExpansionListener( ) methods allow listeners to
register and unregister for these notifications. The
signatures of these methods are shown here:
Void
addTreeExpansionListener(TreeExpansionListener tel)
Void
removeTreeExpansionListener(TreeExpansionListener tel)
Here, tel is the listener object.
The DefaultMutableTreeNode class implements the
MutableTreeNode interface.
It represents a node in a tree. One of its constructors is
shown here:
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node.
To create a hierarchy of tree nodes, the add( ) method of
DefaultMutableTreeNode can be used.
Its signature is shown here:
void add(MutableTreeNode child)
Here, child is a mutable tree node that is to be added as a
child to the current node.
Here are the steps that you should follow to use a tree in
an applet:
1. Create a JTree object.
2. Create a JScrollPane object. (The arguments to the
constructor specify the tree and the policies for vertical
and horizontal scroll bars.)
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane of the applet.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
/*<applet code=JtreeDemo height=300 width=300> </applet> */
public class JtreeDemo extends JApplet
{ public void init() {
Container c=getContentPane();
DefaultMutableTreeNode top=newDefaultMutableTreeNode("Select");
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;