Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Introduction to Swing
Swing API is set of extensible GUI
Components to create JAVA based Front End/
GUI Applications. It is build upon top of AWT
API and acts as replacement of AWT API as it
has almost every control corresponding to
AWT controls.
Swing Features
Light Weight - Swing component are
independent of native Operating System's API as
Swing API controls are rendered mostly using
pure JAVA code instead of underlying operating
system calls.
Rich controls - Swing provides a rich set of
advanced controls like Tree, TabbedPane, slider,
colorpicker, table controls
Pluggable look-and-feel- SWING based GUI
Application look and feel can be changed at run
time based on available values.
Difference between AWT and Swing
N Java AWT Java Swing
o.
1 AWT components are platform- Java swing components
dependent. are platform-independent.
2 AWT components are heavyweight. Swing components are lightweight.
3 AWT doesn't support pluggable Swing supports pluggable look
look and feel. and feel.
4 AWT provides less Swing provides more powerful
components than Swing. componentssuch as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
5 AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.
MVC Architecture
Swing API architecture follows MVC
architecture. The MVC design pattern consists
of three modules: model, view and controller.
Model -The model represents the state (data) and
business logic of the application.
View -The view module is responsible to display data
i.e. it represents the presentation.
Controller -The controller module acts as an
interface between view and model. It intercepts all
the requests i.e. receives input and commands to
Model / View to change accordingly.
Figure: MVC Architecture
JComboBox
Combo box is a combination of text fields and
drop-down list.JComboBox component is used
to create a combo box in Swing.
Constructor for JComboBox
JComboBox()
JComboBox(String arr[])
Methods used with JComboBox
• void addItem(Object anObject)
– Adds an item to the item list.
• void addItemListener(ItemListener aListener)
– Adds an ItemListener.
• Object getItemAt(int index)
– Returns the list item at the specified index.
• int getItemCount()
– Returns the number of items in the list.
• Object getSelectedItem()
– Returns the current selected item.
• void removeAllItems()
– Removes all items from the item list.
• void removeItem(Object anObject)
– Removes an item from the item list.
• void removeItemAt(int anIndex)
– Removes the item at anIndex This method works only if the JComboBox uses a
mutable data model.
import javax.swing.*;
import java.awt.*;
public class comboboxdemo extends JApplet
{
Container c;
JComboBox c1;
public void init()
{
c=getContentPane();
c.setLayout(new FlowLayout());
c1=new JComboBox();
c1.addItem("C Programming");
c1.addItem("C++ Programming");
c1.addItem("Java Programming");
c.add(c1);
}
}
/*<Applet code=comboboxdemo.class Height=400
Width=400></Applet>*/
import javax.swing.*;
public class JComboTest
{
JFrame f;
JComboTest()
{
f=new JFrame("Combo ex");
String country[]={"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JComboTest();
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• Introduction of Swing
• Features of Swing
• Difference between AWT and Swing
• MVC Architecture
• JComboBox Component
JProgressBar
The class JProgressBar is a component which
visually displays the progress of some task.
Constructors of JProgessBar
JProgressBar()
Creates a horizontal progress bar that displays a border
but no progress string.
JProgressBar(int orient)
Creates a progress bar with the specified orientation,
which can be either SwingConstants. VERTICAL or
SwingConstants.HORIZONTAL.
JProgressBar(int min, int max)
Creates a horizontal progress bar with the specified
minimum and maximum values.
JProgressBar(int orient, int min, int max)
Creates a progress bar using the specified orientation,
minimum and maximum values.
Methods used with JProgressBar
• void setStringPainted(boolean b)
– determines whether the progress bar should display a
progress string.
• int getMaximum()
– Returns the progress bar's maximum value
• int getMinimum()
– Returns the progress bar's minimum value from the
BoundedRangeModel.
• int getOrientation()
– Returns SwingConstants.VERTICAL or
SwingConstants.HORIZONTAL, depending on the
orientation of the progress bar.
Methods used with JProgressBar
• void setValue(int value)
– It is used to set the current value on the
progressbar.
• int setOrientation(int orientation)
– It is used to set the orientation, it may be either
vertical or horizontal by using
SwingConstants.VERTICAL or
SwingConstants.HORIZONTAL constants.
• void setString(String s)
It is used to set value to the progress string
import javax.swing.*;
import java.applet.*;
import java.awt.*;
public class progressdemo extends JApplet
{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
JProgressBar p=new
JProgressBar(SwingConstants.HORIZONTAL,00,100);
p.setValue(80);
p.setStringPainted(true);
c.add(p);
}
}
/*<Applet code=progressdemo.class height=400
width=400></Applet>*/
import javax.swing.*;
import java.applet.*;
import java.awt.*;
public class progressdemo extends JFrame
{
progressdemo()
{
setLayout(new FlowLayout());
JProgressBar p=new
JProgressBar(SwingConstants.HORIZONTAL,00,100);
p.setValue(80);
p.setStringPainted(true);
add(p);
}
public static void main(String args[])
{
progressdemo p1=new progressdemo();
p1.setTitle("ProgressBar Demo");
p1.setSize(400,400);
p1.setVisible(true);
p1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
);
}
}
JPanel
A panel is a swing container which is
used for grouping components which is later
on added to the frame. In java swing panel is
implemented by JPanel class.
Constructors of JPanel
JPanel()
Creates a panel.
JPanel(LayoutManager)
The LayoutManager parameter provides
a layout manager for the new panel. By
default, a panel uses a FlowLayout to lay out
its components.
import javax.swing.*;
import java.io.*;
class B
{
public static void main(String arg[])
{
JFrame f=new JFrame("this is my new frame");
JPanel p=new JPanel();
f.add(p);
f.setSize(200,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• JProgressBar Component
• JPanel Container
JScrollPane
• A JScrollPane provides a scrollable view
of a component. When screen real estate is
limited, use a scroll pane to display a
component that is large or one whose size can
change dynamically. i.e. It represents a
scrollpane which is a rectangular area in which
a component may be viewed.
• Horizontal or vertical scroll bars may be
provided if necessary.
Constructors of JScrollPane
JScrollPane(Component com)
com is component which is added to scroll
pane.
JScrollPane(int vsb, int hsb)
vsb and hsb are int constants for controlling vertical
and horizontal scrolling.
JScrollPane(Component com, int vsb, int hsb)
com is component which is added to scroll pane and
vsb and hsb are int constants for controlling vertical
and horizontal scrolling.
int constants vsb nad hsb can have the values:
• VERTICAL_SCROLLBAR_ALWAYS
– Vertical scroll bar is always provided.
• HORIZONTAL_SCROLLBAR_ALWAYS
– Horizontal scroll bar is always provided.
• VERTICAL_SCROLLBAR_AS_NEEDED
– Vertical scroll bar is provided as per the need.
• HORIZONTAL_SCROLLBAR_AS_NEEDED
– Horizontal scroll bar is provided as per the need.
Steps for Creating JScrollPane
1. Create a Component added to ScrollPane,
2. Create a JScrollPane Object.(The arguments
to the constructor specify the component
and the policies for vertical and horizontal
scroll bars.)
3. Add the Component to ScrollPane.
4. Add the ScrollPane to content pane of the
applet.
import javax.swing.*;
import java.awt.*;
import java.applet.*;
public class scrollpanedemo extends JApplet
{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
JButton b=new JButton("OK");
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane s=new JScrollPane(b,v,h);
c.add(s);
}
}
/*<Applet code=scrollpanedemo.class height=400
width=400></Applet>*/
import javax.swing.*;
import java.awt.event.*;
public class scroll {
public static void main(String[] args) {
String s="Welcome to Java Swing programming!!!!! This shows the working of
JScrollPane.....";
JTextArea t=new JTextArea(s,10,10);
JFrame f=new JFrame("Frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane sp=new JScrollPane(t,v,h);
p.add(sp);
f.add(p);
f.setSize(200,200);
f.setVisible(true);
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• JScrollPane Component
JTable
• The JTable class is used to display the
data on two dimensional tables of cells i.e.
rows and columns of data.
• You can drag the cursor on column
boundaries to resize columns. Also you can
drag a column to a new position.
Constructors of JTable class:
JTable()
creates a table with empty cells.
JTable(Object data[][], Object colHeads[])
Here, data is a two-dimenstional array of the
information to be persented, and colHeads is a
one-dimenstional array with the column
headings.
Steps to Create JTable Component
1. Create JTable Object with data and columns
titles.
2. Create a JScrollPane Object.(The arguments to
the constructor specify the component and
the policies for vertical and horizontal scroll
bars.)
3. Add JTable Component to JScrollPane.
4. Add the JScrollPane to content pane of Applet.
import javax.swing.*;
import java.awt.*;
import java.applet.*;
public class JTabledemo extends JApplet {
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
final String data[][]={
{"101","Umesh","670000"},
{"102","Vijay","780000"},
{"101","Rahul","700000"}};
final String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane sp=new JScrollPane(jt,v,h);
c.add(sp);
}
}
/*<Applet code=JTabledemo.class height=400 width=400></Applet>*/
import javax.swing.*;
public class MyJTable extends JFrame {
MyJTable()
{
String data[][]={
{"101","Umesh","670000"},
{"102","Vijay","780000"},
{"101","Rahul","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
add(sp);
setSize(300,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyJTable();
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• JTable Component
JTabbedPane
• JTabbedPane is a component which
appears as a group of multiple tabs, each
containing a title and a Panel as a group of
components.
• When user selects a tab, its contents becomes
visible and user can interact with it.
• The main purpose of tabbed panes is to
provide configuration related options.
Constructors for JTabbedPane
JTabbedPane()
Creates an empty TabbedPane with a default tab
placement of JTabbedPane.TOP. The addTab() method is
used to add different tab to tabbed pane.
JTabbedPane(int tabPlacement)
Creates an empty TabbedPane with the specified
tab placement of either: JTabbedPane.TOP,
JTabbedPane.BOTTOM, JTabbedPane.LEFT, or
JTabbedPane.RIGHT.
JTabbedPane(int tabPlacement, int tabLayoutPolicy)
Creates an empty TabbedPane with the specified
tab placement and tab layout policy.
Tab Layout policy are:
• JTabbedPane.WRAP_TAB_LAYOUT
• JTabbedPane.SCROLL_TAB_LAYOUT
Tabs are 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.
Steps to Create JTabbedPane
• Create a JTabbedPane Object.
• Call addTab() to add a tab to the pane.(The
arguments to this method define the title of
the tab and the component it contain.)
• Repeat Step 2 for each tab.
• Add the tabbed pane to Applet/Frame.
import javax.swing.*;
/* <applet code="exp43" width=400 height=100> </applet> */
public class exp43 extends JApplet
{
public void init()
{
JTabbedPane exp43 = new JTabbedPane();
exp43.addTab("Cities", new CitiesPanel());
exp43.addTab("Colors", new ColorsPanel());
exp43.addTab("Flavors", new FlavorsPanel());
add(exp43);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("Kolhapur");
add(b1);
JButton b2 = new JButton("Karad");
add(b2);
JButton b3 = new JButton("Satara");
add(b3);
JButton b4 = new JButton("Pune");
add(b4);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TabbedPane extends JFrame
{
JTabbedPane tabs;
CoursePanel cource;
SelectCoursePanel selectCourse;
TabbedPane() {
super("Tabbed Pane Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
cource = new CoursePanel();
selectCourse = new SelectCoursePanel();
tabs.addTab("Cources", cource);
tabs.addTab("Select Course", selectCourse);
tabs.addTab("Listing", new JPanel());
tabs.addTab("Comment", new JTextArea(10, 40));
tabs.addTab("Register", new JPanel());
tabs.addTab("Contact Us", new JPanel());
tabs.addTab("More..", new JPanel());
getContentPane().add(tabs);
}
class CoursePanel extends JPanel {
JButton addCourse, clear;
CoursePanel() {
addCourse = new JButton("Add Course");
clear = new JButton("Clear");
setLayout(new FlowLayout());
add(addCourse);
add(clear);
}
}
class SelectCoursePanel extends JPanel
{
JCheckBox java, swing, hibernate;
SelectCoursePanel() {
java = new JCheckBox("Java");
swing = new JCheckBox("Spring");
hibernate = new JCheckBox("Hibernate");
setLayout(new FlowLayout());
add(java);
add(swing);
add(hibernate);
}
}
public static void main(String args[]) throws Exception {
TabbedPane frame = new TabbedPane();
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• JTabbedPane Component
JTree
• JTree class is a powerful Swing component for
displaying tree-structured data.
• A JTree object does not actually contain your data; it
simply provides a view of the data. Like any non-
trivial Swing component, the tree gets data by
querying its data model. Here is a picture of a tree:
Each row displayed by the tree contains exactly
one item of data, which is called a node.
Every tree has a root node from which all
nodes descend.
A node can either have children or not.
We refer to nodes that can have children
as branch nodes. Nodes that can not have
children are leaf nodes.
Branch nodes can have any number of children.
A specific node in a tree can be identified
either by a TreePath, an object that
encapsulates information about the node, or
by its display row, where each row in the
display area displays one node.
An expanded node is a non-leaf node that will
display its children when all its ancestors are
expanded.
A collapsed node is one which hides them.
A hidden node is one which is under a
collapsed ancestor.
Constructors Of JTree
• JTree(Hashtable ht)
– Returns a JTree created from a Hashtable which does not
display with root. Each element of hashtable is a childnode.
• JTree(Object[] value)
– Returns a JTree with each element of the specified array as
the child of a new root node which is not displayed. Each
element of the array object is childnode.
• JTree(TreeNode root)
– Returns a JTree with the specified TreeNode as its root, which
displays the root node. Treenode tn is the root of the tree.
• JTree(Vector v)
– Returns a JTree with each element of the specified Vector as
the child of a new root node which is not displayed. Elements
of vector v is the childnode
• It is possible to obtain a reference to the
parent node.
• The ‘MutableTreeNode’ interface extends
‘TreeNode’, which is an interface that declares
methods that obtain information about a tree
node.
• The ‘DefaultMutableTreeNode’ class
implements the ‘MutableTreeNode’ interface.
It represents a node in a tree.
Methods used with JTree
DefaultMutableTreeNode(object obj)
where ‘obj’ is the object to be enclosed in this tree
node.
void add(MutableTreeNode child)
This method can be used to create the hierarchy of
nodes .where ‘child’ is the mutable treenode this is
to be added as a child to the current node.
TreePath getPathForLocation(int x, int y)
It is used to translate a mouse click on a point of
tree to a tree path. Where, x and y are coordinates
of mouse click.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class tree1 extends JApplet
{
public void init()
{
Container c=getContentPane();
DefaultMutableTreeNode root=new DefaultMutableTreeNode("SPM
Polytechnic");
DefaultMutableTreeNode branch=new DefaultMutableTreeNode("Computer
Engineering");
DefaultMutableTreeNode branch1=new
DefaultMutableTreeNode("Mechanical Engineering");
DefaultMutableTreeNode branch2=new
DefaultMutableTreeNode("Electronics & Telecommunication Engineering");
root.add(branch);
root.add(branch1);
root.add(branch2);
JTree tree=new JTree(root);
c.add(tree);
}
}
/*<Applet code=tree1.class height=400 width=400></Applet>*/
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class tree
{
public static void main(String[] args)
{
wood o=new wood();
o.wod();
}
}
class wood extends JFrame
{
public void wod()
{
JFrame f=new JFrame();
DefaultMutableTreeNode root=new DefaultMutableTreeNode("Asia");
DefaultMutableTreeNode country=new
DefaultMutableTreeNode("India");
DefaultMutableTreeNode state=new DefaultMutableTreeNode("Madhya
Pradesh");
DefaultMutableTreeNode city=new DefaultMutableTreeNode("Gwalior");
root.add(country);
country.add(state);
state.add(city);
JTree tree=new JTree(root);
f.add(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,300);
f.setVisible(true);
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• JTree Component
ToolTip
Tooltip text is normally one line long. The
setToolTipText() method from JComponent
used to create a tooltip.
public void setToolTipText(String text)
-Registers the text to display in a tool tip.
The text displays when the cursor lingers over
the component.
import javax.swing.*;
public class Tooltipdemo extends JApplet
{
public void init()
{
JButton b = new JButton("Test");
b.setToolTipText("Help text for the button");
getContentPane().add(b,"Center");
}
}
/*<Applet code=Tooltipdemo.class height=400 width=400></Applet>*/
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonWithTooltip extends JFrame
{
public JButtonWithTooltip()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Test");
b.setToolTipText("Help text for the button");
getContentPane().add(b, "Center");
}
public static void main(String[] args)
{
new JButtonWithTooltip().setVisible(true);
}
}
JSeparators
The JSeparator class provides a horizontal or
vertical dividing line or empty space. It's most
commonly used in menus and tool bars.
Separators are similar to borders, except that
they are genuine components and are drawn
inside a container, rather than around the edges
of a particular component.
Menus and tool bars provide convenience
methods that create and add separators
customized for their containers.
menu.addSeparator();
Consrtuctors for JSeparators
JSeparator()
Create a separator. If you don't specify an
argument, the separator is horizontal.
JSeparator(int)
The argument can be either
SwingConstants.HORIZONTAL or
SwingConstants.VERTICAL.
import javax.swing.*;
public class MenuSeparator extends JFrame
{
public MenuSeparator()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
bar.add(menu);
menu.add(new JMenuItem("Close"));
menu.add(new JSeparator()); // SEPARATOR
menu.add(new JMenuItem("Exit"));
setJMenuBar(bar);
getContentPane().add(new JLabel("A placeholder"));
setSize(300, 300);
setVisible(true);
}
public static void main(String arg[])
{
new MenuSeparator();
}
}
import java.awt.*;
import javax.swing.*;
public class AnotherSeparatorSample
{
public static void main(String args[])
{
JFrame f = new JFrame("JSeparator Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new GridLayout(0, 1));
JLabel above = new JLabel("Above Separator");
content.add(above);
JSeparator separator = new JSeparator();
content.add(separator);
JLabel below = new JLabel("Below Separator");
content.add(below);
f.setSize(300, 100);
f.setVisible(true);
}
}
Advanced Java Programming
Unit-2
Swings
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• JToolTip Component
• JSeperator Component
ImageIcon & JLabel Component
• In Swing, icons are encapsulated by the ImageIcon
class, which paints an icon from an image.
• Two of its constructors are shown here:
1. ImageIcon(String filename)
2. 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.
Methods of ImageIcon
Constructor of JLabel
• JLabel(Icon i)
• JLabel(String s)
• JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for
the label. The align argument is either LEFT, RIGHT,
CENTER, LEADING, or TRAILING. These constants
are defined in the SwingConstants interface, along
with several others used by the Swing classes.
Methods of JLabel Component
• The icon and text associated with the label can
be read and written by the following methods:
• Icon getIcon( )
• String getText( )
• void setIcon(Icon i)
• void setText(String s)
Here, i and s are the icon and text,
respectively.
import javax.swing.*;
import java.awt.*;
import java.applet.*;
public class Imagedemo extends JApplet
{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
ImageIcon i=new ImageIcon("OIP.gif");
JLabel l=new JLabel("Name",i,JLabel.CENTER);
c.add(l);
}
}
/*<Applet code=Imagedemo.class height=400 width=400></Applet>*/
JTextField Component
The Swing text field is encapsulated by the
JTextComponent class, which extends JComponent. It provides
functionality that is common to Swing text components. One of
its subclasses is JTextField, which allows us to edit one line of
text. Some of its constructors are shown here:
• JTextField( )
• JTextField(int cols)
• JTextField(String s, int cols)
• JTextField(String s)
• Here, s 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="JTextFieldDemo" width=300 height=50></applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
JButton Component
The JButton class provides the functionality of a
push button. JButton allows an icon string, or both to be
associated with the push button. Some of its
constructors are shown here:
• JButton(Icon i)
• JButton(String s)
• JButton(String s, Icon i)
Here, s and i are the string and icon used for the
button.
import java.awt.*;
import javax.swing.*;
/*<applet code="JButtonDemo" width=250 height=300></applet>*/
public class JButtonDemo extends JApplet
{
public void init()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
ImageIcon france = new ImageIcon("france.gif");
JButton b1= new JButton(france);
ImageIcon germany = new ImageIcon("germany.gif");
JButton b2= new JButton(germany);
ImageIcon itely = new ImageIcon("itealy.gif");
JButton b3= new JButton(itely);
c.add(b1);
c.add(b2);
c.add(b3);
}
}
JCheckBox Component
The JCheckBox class, which provides the functionality of a
check box, is a concrete implementation of Abstract Button. It is
immediate super -class is JToggleButton, which provides support
for two -state buttons. Some of its constructors are shown here:
• JCheckBox(Icon i)
• JCheckBox(Icon i, boolean state)
• JCheckBox(String s)
• JCheckBox(String s, boolean state)
• JCheckBox(String s, Icon i)
• JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is
specified by s. If state is true, the check box is initially
selected. Otherwise, it is not. The state of the check
box can be changed via the following method:
• void setSelected(boolean state)
Here, state is true if the check box should be
checked.
JRadioButton Component
Radio buttons are supported by the JRadioButton class,
which is a concrete implementation of Abstract Button. Its
immediate super -class is JToggle Button, which provides
support for two- state buttons. Some of its constructors are
shown here:
• JRadioButton(Icon i)
• JRadioButton(Icon i, boolean state)
• JRadioButton(String s)
• JRadioButton(String s, boolean state)
• JRadioButton(String s, Icon i)
• JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text
is specified by s. If state is true, the button is
initially selected. Otherwise, it is not. Radio
buttons must be configured into a group. Only
one of the buttons in that group can be selected
at any time.
ButtonGroup Component
The ButtonGroup class is instantiated to
create a button group. Its default constructor is
invoked for this purpose. Elements are then added
to the button group via the following method:
• void add(AbstractButton ab)
Here, ab is a reference to the button to be
added to the group.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code="JRadioButtonDemo" width=400 height=50></applet> */
public class JRadioButtonDemo extends JApplet
{
public void init()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
ImageIcon i1=new ImageIcon("twitter.gif");
JRadioButton b1 = new JRadioButton("A",i1,true);
c.add(b1);
JRadioButton b2 = new JRadioButton("B");
c.add(b2);
JRadioButton b3 = new JRadioButton("C");
c.add(b3);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
ImageIcon i2=new ImageIcon("wekipedia.gif");
JCheckBox c1=new JCheckBox("Programming in C",i2,false);
c.add(c1);
}
JToggleButton
A toggle button is two-states button that allows
user to switch on and off. To create a toggle
button JToggleButton class is used.
Constructors for JToggleButton
JToggleButton( )
Creates a toggle button without text and icon.
The state of toggle button is not selected.
JToggleButton(String text)
Creates a toggle button with text
JToggleButton(String text, boolean selected)
Creates a toggle button with text and initialize
the state of the toggle button
import java.awt.*;
import javax.swing.*;
public class ToggleButtonSample
{
public static void main(String args[])
{
JFrame f = new JFrame("JToggleButton Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.add(new JToggleButton("North"), BorderLayout.NORTH);
content.add(new JToggleButton("East"), BorderLayout.EAST);
content.add(new JToggleButton("West"), BorderLayout.WEST);
content.add(new JToggleButton("Center"),BorderLayout.CENTER);
content.add(new JToggleButton("South"), BorderLayout.SOUTH);
f.setSize(300, 200);
f.setVisible(true);
}
}
Using Top-Level Containers
Swing provides three generally useful top-level container
classes: JFrame, JDialog, and JApplet.
A container has several layers in it. You can think of a layer as a
transparent film that overlays the container.
In Java Swing, the layer that is used to hold objects is called
the content pane.
Objects are added to the content pane layer of the container.
The getContentPane() method retrieves the content pane layer
so that you can add an object to it.
getContentPane()
Returns the contentPane object for this
container.
import java.awt.*;
import java.applet.*;
import javax.swing.*;
public class GridLayoutExample extends JApplet
{
public void init()
{
Container c = getContentPane();
c.setLayout(new GridLayout(2, 4));
c.add(new JButton("One"));
c.add(new JButton("Two"));
c.add(new JButton("Three"));
c.add(new JButton("Four"));
c.add(new JButton("Five"));
}
}
import java.awt.*;
import javax.swing.*;
public class Frame4a
{
public static void main(String[] args)
{
JFrame f = new JFrame("JFrame with a JPanel");
JLabel L = new JLabel("Hello World !");
JPanel P = new JPanel(); // Make a Jpanel
P.add(L);
f.getContentPane().add(P);
f.setSize(400,300);
f.setVisible(true);
}
}