Unit 2
Unit 2
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications.
It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Swing is a set of classes that provides more powerful and flexible components than are
possible with the AWT.
In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies
several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it.
Also, the image can be changed as the state of the button changes.
Unlike AWT components, Swing components are not implemented by platform-specific
code.
Instead, they are written entirely in Java and, therefore, are platform-independent.
The term lightweight is used to describe such elements.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development
of desktop applications.
Hierarchy of Java Swing classes
Commonly used Methods of Component class
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
Containers
There are two types of containers :
Top-Level Containers
A top-level container, as the name suggests, lies at the top of the containment hierarchy. The
top-level containers are JFrame, JApplet, and JDialog. These containers do not inherit
JComponent class but inherit the AWT classes’ Component and Container. These
containers are heavyweight components. The most commonly used containers are JFrame
and JApplet.
Lightweight Containers
Lightweight containers lie next to the top-level containers in the containment hierarchy. They
inherit JComponent. One of the examples of lightweight container is JPanel.
As lightweight container can be contained within another container, they can be used to
organize and manage groups of related components.
Java Swing Examples
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame(); //creating instance of JFrame
JButton b=new JButton("click"); //creating instance of JButton
b.setBounds(130,100,100, 40); //x axis, y axis, width, height
f.add(b); //adding button in JFrame
f.setSize(400,500); //400 width and 500 height
f.setLayout(null); //using no layout managers
f.setVisible(true); //making the frame visible
}
}
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.
( JLabel.LEFT, JLabel.CENTER, JLabel.RIGHT)
Commonly used Methods:
Methods Description
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
ImageIcon i = new ImageIcon("D:\\icon.png");
JLabel l1,l2;
l1=new JLabel(i);
l1.setBounds(50,50,150,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.
JTextField(int columns) Creates a new empty TextField with the specified number
of columns.
Methods Description
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.
Constructor Description
Example:
import javax.swing.*;
public class PasswordFieldExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value);
f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample extends JFrame implements ActionListener
{
JLabel label;
JTextField text;
JPasswordField pass;
PasswordFieldExample ()
{
label = new JLabel();
label.setBounds(20,150,300,50);
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
text= new JTextField();
text.setBounds(100,20, 100,30);
add(pass);
add(l1);
add(label);
add(l2);
add(b);
add(text);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String data1 = text.getText();
String data2 = new String (pass.getPassword());
String data3 = "Username :" +data1+ ", Password :"+data2;
label.setText(data3);
}
}
}
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not
selected) it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Example 1:
import javax.swing.*;
public class CheckBoxExample
{
public static void main(String args[])
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100,100,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150,100,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JCheckBox Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample f ;
CheckBoxExample()
{
l=new JLabel("Food Ordering System");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);
add(cb1);
add(cb2);
add(cb3);
add(b);
}
public void actionPerformed(ActionEvent e)
{
float amount=0;
String msg="";
if(cb1.isSelected())
{
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected())
{
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected())
{
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(f,msg+"Total: "+amount);
}
public static void main(String[] args)
{
CheckBoxExample f = new CheckBoxExample();
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
JRadioButton(String s, boolean Creates a radio button with the specified text and selected status.
selected)
void removeAllItems() It is used to remove all the items from the list.
Example 1:
import javax.swing.*;
public class ComboBoxExample
{
public static void main(String[] args)
{
JFrame f = new JFrame(“ComboBox Example”);
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
}
Example 2
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample extends JFrame implements ActionListener
{
JComboBox cb;
JLabel label;
ComboBoxExample()
{
label = new JLabel();
label.setBounds(50,50,400,30);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
cb=new JComboBox(languages);
cb.setBounds(20,100,90,20);
add(cb);
add(label);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
public static void main(String[] args)
{
ComboBoxExample f = new ComboBoxExample();
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
}
}
Tabbed Panes
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.
There are three constructors of JtabbedPane
1. JTabbedPane ( )
The constructor JTabbedPane ( ) creates an empty TabbedPane. When we use the constructor
JTabbedPane ( ), it creates the pane without any specification for its placement. So the tab is
placed on its default place that is TOP as discussed above using JTabbedPane.TOP.
With the policy set to SCROLL_TAB_LAYOUT, the tabs become scroll-able and a button for
scrolling the tabs, left-right or up-down, is displayed in your tabbed pane.
Example:
import javax.swing.*;
class AddJTabbedPane
{
public static void main(String[] args)
{
JTabbedPane tp;
JLabel lab1, lab2, lab3, lab4, lab5, lab6, lab7, lab8;
JPanel fruit, vegetable;
JFrame frame=new JFrame("JTabbedPane Example");
fruit = new JPanel();
lab1=new JLabel("Apple");
lab2=new JLabel("Orange");
lab3=new JLabel("Papaya");
lab4=new JLabel("Pine Apple");
fruit.add(lab1);
fruit.add(lab2);
fruit.add(lab3);
fruit.add(lab4);
tp=new JTabbedPane();
tp.addTab("Fruit",fruit);
tp.addTab("Vegetable",vegetable);
tp.setBounds(50,50,200,200);
frame.add(tp);
frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
JScrollPane
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.
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 this scroll pane are shown. 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. (The arguments to the constructor specify the component and
the policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.
Example
import javax.swing.*;
import java.awt.*;
public class JScrollPaneDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Scroll Pane Example");
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
jp.add(new JButton("Button " + b));
++b;
}
}
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
frame.add(jsp,BorderLayout.CENTER);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Java JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.
The object of JMenu class is a pull down menu component which is displayed from the menu
bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.
import javax.swing.*;
import java.awt.event.*;
public class MenuExample extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample()
{
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectAll);
mb.add(file);
mb.add(edit);
mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
add(mb);
add(ta);
setJMenuBar(mb);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args)
{
MenuExample f = new MenuExample();
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
}
Java JTree
The JTree class is used to display the tree structured data or hierarchical data.
JTree is a complex component. It has a 'root node' at the top most which is a parent for all nodes
in the tree.
Trees are implemented in Swing by the JTree class, which extends JComponent.
Commonly used Constructors:
Constructor Description
JTree(Object[] value) Creates a JTree with every element of the specified array as the child of
a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays
the root node.
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node.
The new tree node doesn’t have a parent or children.
To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be
used.
import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
public class Tree2
{
public static void main(String args[])
{
JFrame jf = new JFrame("JTree");
JLabel label1 = new JLabel("Displaying tree");
jf.add(label1);
jf.add(jsp,BorderLayout.CENTER);
jf.setSize(300,200);
jf.setVisible(true);
}
}
JTable
In Java, JTable is used to edit or display 2-D data which consists of rows and columns. It is
almost similar to a spreadsheet that contains data in a tabular form.
JTable can be created by instantiating the class javax.swing.JTable.
Java JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits JComponent class.
JProgressBar(int min, It is used to create a horizontal progress bar with the specified minimum and
int max) maximum value.
JProgressBar(int It is used to create a progress bar with the specified orientation, it can be
orient) either Vertical or Horizontal by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int orient, It is used to create a progress bar with the specified orientation, minimum
int min, int max) and maximum value.
void setOrientation(int It is used to set the orientation, it may be either vertical or horizontal by
orientation) using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL
constants.
void setValue(int value) It is used to set the current value on the progress bar.
Example:
import javax.swing.*;
public class ProgressBarExample extends JFrame
{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample()
{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate()
{
while(i<=2000)
{
jb.setValue(i);
i=i+20;
try
{
Thread.sleep(150);
}
catch(Exception e){}
}
}
public static void main(String[] args)
{
ProgressBarExample m=new ProgressBarExample();
m.setVisible(true);
m.iterate();
}
}