0% found this document useful (0 votes)
47 views

Introduction To Swing

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Introduction To Swing

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

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:

HORIZONTAL_SCROLLBAR_ALWAYS :- Always provide


horizontal scroll bar
HORIZONTAL_SCROLLBAR_AS_NEEDED:- Provide
horizontal scroll bar, if needed
VERTICAL_SCROLLBAR_ALWAYS :- Always provide
vertical scroll bar
VERTICAL_SCROLLBAR_AS_NEEDED :- Provide
vertical scroll bar,if needed
Here are the steps that you should follow to use a scroll pane
in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object with the constructor and the its
parameter as listed in the previous point
3. Add the scroll pane to the content pane of the applet.
 import java.awt.*;
 import javax.swing.*;
 /*<applet code="JScrollDemo" height=100
width=100></applet> */
 public class JScrollDemo extends JApplet
 { public void init() {
 char b='A';
 Container c=getContentPane();
 c.setLayout(new GridLayout(5,5));
 for(int i=0;i<5;i++)
{
 for(int j=0;j<5;j++)
{
 c.add(new JButton("Button"+b));
 ++b;
}
}
 int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
 int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

 JScrollPane js=new JScrollPane(v,h);


 c.add(js);
}
}
JComboBox
Swing provides a combo box which is a combination of a text
field and a drop-down list through the JComboBox class,
which extends JComponent.
A combo box normally displays one entry at time in the given
set of elements. However, it can also display a drop-down list
that allows a user to select a different entry.
We can also type your selection into the text field.
Two of JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)
In the constructor,v is the vector used to initialize the combo
box
Next step is to add the items
Items are added to the list of choices via the addItem( )
method, whose signature is shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
 import java.awt.*;
 import javax.swing.*;
 /*<applet code="JComboDemo" height=100 width=100> </applet> */
 public class JComboDemo extends JApplet
{
 public void init() {
 Container c=getContentPane();
 c.setLayout(new FlowLayout(FlowLayout.LEFT));
 JComboBox jc=new JComboBox();
 jc.addItem("Yahoo");
 jc.addItem("Gmail");
 jc.addItem("Twitter");
 jc.addItem("Facebook");
 c.add(jc);
} }
JToggleButton
Toggle button is used to use it like a switch having two
stages called on or off.
Stages could be yes or no,same button can be pressed
to either enable it or disable it.
AbstractButton is implemented by JToggleButton
It defines the following Constructor as:
JToggleButton(String str)
It creates a toggle button with String str
Methods defined by ToggleButton are:
Object getItem()-used to get the item
 isSelected() –it returns true or false
import java.awt.*;
import javax.swing.*;
/*<applet code="JToggleDemo" height=100 width=100>
</applet> */
public class JToggleDemo extends JApplet
{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
JToggleButton jb=new JToggleButton("ON/OFF");
c.add(jb);
}
}
JProgressBar
 JProgressBar is one of the important component of java that
indicates progress of some task.
 We usually see this progress bar while installation of some
software is going on.
 Constructors:
JProgressBar()
JProgressBar(int orient)
JProgressBar(int min,int max)
 First form creates horizontal progress bar
 In Second form,value of int orient could be
 SwingConstants.VERTICAL
 SwingConstants.HORIZONTAL
Third form creates Horizontal progress bar with the specified
minimum and maximum values
ProgressBar defines the following Methods:
int getMaximum()-returns the max value of progress bar
int getMinimum()-returns the min value of progress bar
int getOrientation()-returns the orientation of progress bar
 import java.awt.*;
 import java.applet.*;
 import javax.swing.*;
 /*<applet code=JProgressDemo height=200 width=200>
</applet> */
 public class JProgressDemo extends JApplet
 { public void init() {
 Container c=getContentPane();
 c.setLayout(new FlowLayout());
 JProgressBar jp=new JProgressBar();
 JProgressBar jp1=new
JProgressBar(SwingConstants.VERTICAL);
 c.add(jp);
 c.add(jp1);
} }
JTooltip
Tooltip is kind of a notification shown to indicate some
information,we can create tooltip to any JComponent
object
We can use setTooltipText() mtd for setting up the tooltip.
For ex,to add tooltip for a single button,we can write in
the following way as:
B1.setToolTipText(“Tooltip on Button Component”)
It defines the following Methods:
setToolTipText(String str)
String getToolTipText()
String getToolTipText(MouseEvent)
Pointer getTooltipLocation(MouseEvent)
 import javax.swing.JButton;
 import javax.swing.JFrame;
 public class JTooltipDemo extends JFrame
{
 public static void main(String args[])
{
 JTooltipDemo jf=new JTooltipDemo();
 JButton jb=new JButton("Welcome To AJP");
 jf.add(jb,"Center");
 jb.setToolTipText("ToolTip Notification Program");
 jf.setSize(300,200);
 jf.setVisible(true);
} }
JSeperator
This Component is mainly used to implement divider
lines
It is mostly used as line divider in menu item,Menu
items that may break into logical groups
It can be used in frame also to divide the lines on the
frame and place the components at the required places
Constructors are:
JSeparator()
JSeparator(int orientation)
Methods are:
getOrientation()
setOrientation(int orientation)
 import java.awt.*;
 import javax.swing.*;
 import javax.swing.JSeparator;
 public class JSepDemo extends JFrame
 { public static void main(String args[])
 { JSepDemo jf=new JSepDemo();
 Container c=jf.getContentPane();
 c.setLayout(new GridLayout(0,1));
 JLabel jl=new JLabel("AJP",JLabel.CENTER); c.add(jl);
 JSeparator js=new JSeparator();
 c.add(js);
 JButton jb=new JButton("CSR"); c.add(jb);
 jf.setSize(300,100);
 jf.setVisible(true);
} }
JTabbedPane
A tabbed pane is a component that appears as a group of folders
in a file cabinet. Each folder has a title. When a user selects a
folder, its contents become visible.
Only one of the folders may be selected at a time. Tabbed panes
are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which
extends JComponent. We will use its default constructor.
JTabbedPane()
Tabs are defined or added via the following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is the component that
should be added to the tab.
Typically, a JPanel or a subclass of it is added.
The general procedure to use a tabbed pane in an applet is
outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to
this method define the title of the tab and the component it
contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.
 import java.awt.*;
 import javax.swing.*;
 /*<applet code=JTabPaneDemo height=200 width=200>
</applet>*/
 public class JTabPaneDemo extends JApplet
{ public void init()
{
 Container c=getContentPane();
 JTabbedPane jtp=new JTabbedPane();
 jtp.addTab("First Year",new FYPanel());
 jtp.addTab("Second Year",new SYPanel());
 jtp.addTab("Third Year",new TYPanel());
 c.add(jtp);
}
}
 class FYPanel extends JPanel
{
 public FYPanel()
{
 JButton j=new JButton("CHEM");
 JButton j1=new JButton("PHY");
 JButton j2=new JButton("MTHS");
 add(j); add(j1); add(j2);
} }

 class SYPanel extends JPanel


{
 public SYPanel()
{
 JLabel j=new JLabel("RDM");
 JLabel j1=new JLabel("OOP");
 JLabel j2=new JLabel("MAP");
 add(j); add(j1); add(j2);
}
}
 class TYPanel extends JPanel
 { public TYPanel()
 { JCheckBox j=new JCheckBox("AJP");
 JCheckBox j1=new JCheckBox("CSR");
 JCheckBox j2=new JCheckBox("MGMT");
 add(j); add(j1); add(j2);
} }
JTables
A table is a collection of rows and columns
A table is a component that displays data in the form of rows
and columns
Tables are implemented by the JTable class, which extends
JComponent.
One of its constructors is shown here:
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.
Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object with constructor and parameter
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.

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

 //Tree for Colors


 DefaultMutableTreeNode col=new DefaultMutableTreeNode("Colors");
 top.add(col);
 DefaultMutableTreeNode red=new DefaultMutableTreeNode("Red");
 col.add(red);
 DefaultMutableTreeNode grn=new DefaultMutableTreeNode("Green");
 col.add(grn);
 DefaultMutableTreeNode blue=new DefaultMutableTreeNode("Blue");
 col.add(blue);

 //Tree for Fruits


 DefaultMutableTreeNode fr=new DefaultMutableTreeNode("Fruits");
 top.add(fr);
 DefaultMutableTreeNode or=new DefaultMutableTreeNode("Orange");
 fr.add(or);
 DefaultMutableTreeNode man=new
DefaultMutableTreeNode("Mango");
 fr.add(man);
 DefaultMutableTreeNode app=new DefaultMutableTreeNode("Apple");
 fr.add(app);

 JTree jt=new JTree(top);

 int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
 int
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

 JScrollPane jsp=new JScrollPane(jt,v,h);


 c.add(jsp);
}
}

You might also like