Unit 4 Chapter 2
Unit 4 Chapter 2
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications.
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 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.
Light Weight − Swing components 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.
Platform Independence: One of the primary advantages of Swing is its platform
independence. Applications developed using Swing can run on any platform that supports Java,
without requiring modifications.
Rich Set of Components: Swing offers a wide range of components that can be used to create
complex GUIs. Developers can choose from basic components like buttons and labels to
advanced components such as tables, trees, and scroll panes.
Event Handling: Swing provides a robust event handling mechanism that allows developers
to respond to user interactions, such as button clicks and mouse movements. This enables the
creation of interactive and responsive applications.
Layout Managers: Swing includes a set of layout managers that facilitate the arrangement
of components within a container. Layout managers automatically adjust the position and
size of components based on the container's size,.
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
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.
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 JScrollPane.
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 JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
public ButtonExample()
{
tf=new JTextField();
tf.setBounds(50,50,200,20);
b.addActionListener(this);
add(b);
add(tf);
}
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, and
horizontalAlignment) 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 columns) Creates a new TextField initialized with the specified text
and columns.
JTextField(int columns) Creates a new empty TextField with the specified number
of columns.
Commonly used Methods:
Methods Description
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
class Sample extends JFrame implements ActionListener
{
JTextField tf1,tf2,tf3;
JButton b1,b2,b3,b4;
Sample()
{
tf1.setBounds(50,50,100,30);
tf2.setBounds(50,100,100,30);
tf3.setBounds(50,150,100,30);
b1.setBounds(50,200,50,50);
b2.setBounds(110,200,50,50);
b3.setBounds(170,200,50,50);
b4.setBounds(230,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(b4);
}
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c=0;
if(e.getSource()== b1)
{
c= a+b;
}
else if(e.getSource()==b2)
{
c=a-b;
}
else if(e.getSource()==b3)
{
c=a*b;
}
else if(e.getSource()==b4)
{
c=a/b;
}
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not
selected) it is initially selected.
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 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 removeItem(Object anObject) It is used to delete an item from the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) the boolean b determines whether the combo box is editable or
not. If true is passed then the combo box is editable or vice versa.
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);
}
}
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.
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.*;
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;
Constructor Description
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.
Example:
import javax.swing.*;
import java.awt.*;
public class TableExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
ID Name Salary
101 Amit 670000
102 Jai 780000
103 Sachin 700000
104 Amol 512000
105 Seema 450000
106 Gaurav 750000
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.*;
class Sample extends JFrame
{
JProgressBar jpb;
int i = 0;
Sample()
{
jpb = new JProgressBar(0,2000);
jpb.setBounds(40,40,120,40);
jpb.setValue(0);
jpb.setStringPainted(true);
jpb.setString("Loading");
add(jpb);
setSize(500,500);
setLayout(null);
}
void iterate()
{
while(i<=2000)
{
jpb.setValue(i);
i=i+20;
try
{
Thread.sleep(150);
}
catch(Exception e)
{
}
}