Professional Documents
Culture Documents
Swing in java is part of JFC which is lightweight and platform independent. It is used for
creating window based applications. It includes components like button, scroll bar, text field etc.
Putting together all these components makes a graphical user interface.
Java Foundation Classes (JFC):
JFC is an extension of original AWT.
It contains classes that are completely portable, since the entire JFC is developed in pure
Java.
Some of the features of JFC are:
1. JFC components are light-weight: Means they utilize minimum resources. 2. JFC
components have same look and feel on all platforms. Once a component is created, it
looks same on any OS.
3. JFC offers “pluggable look and feel” feature, which allows the programmer to change
look and feel as suited for platform
4. JFC does not replace AWT, but JFC is an extension to AWT.
So, JFC represents class library developed in pure Java which is an extension to AWT and swing
is one package in JFC, which helps to develop GUIs and the name of the package is import
javax.swing.*; Here x represents that it is an ‘extended package’ whose classes are derived from
AWT package. The classes in the javax.swing package begins with the letter ‘J’. So in a
javax.swing package, we will have classes like JButton, JFrame, JTextField, JTextArea, etc.
1. Swing is written in pure Java (except a few classes) and therefore is 100% portable.
2. Swing components are lightweight. The AWT components are heavyweight (in terms of
system resource utilization).
3. Swing components support pluggable look-and-feel.
4. Swing supports mouse-less operation, i.e., it can operate entirely using keyboard.
Container Class
Containers are an integral part of SWING GUI components. A container provides a space where
a component can be located. A Container in AWT is a component itself and it provides the
capability to add a component to itself. Following are certain noticeable points to be considered.
Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be overridden
using setLayout method.
Any class which has other components in it is called as a container class. For building GUI
applications at least one container class is necessary.
Following are the three types of container classes:
1. Panel – It is used to organize components on to a window
3. Dialog – It is like a pop up window but not fully functional like the frame
3. Make the Frame object appear on the screen by calling setVisible () method.
4. In order to close the window by clicking the close(X) button, you will have to insert the
code for window closing event.
Frame ()
Frame (String)
dispose ()
getTitle ()
isResizable ()
setMenuBa (MenuBar)
setResizable (Boolean)
Specifies whether or not the window is sizable.
setTitle (String)
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
panel.setLayout(new FlowLayout());
button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
The following FrameDemo code shows how to create and set up a frame.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.pack();
//5. Show it.
frame.setVisible(true);
1. JButton Class
The JButton class represents a button: a user interface component that the user can click to
initiate an action. It is used to create a labelled button. Using the ActionListener it will result in
some action when the button is pushed. It inherits the AbstractButton class and is platform
independent.
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
Java JButton Example with ActionListener-Action listeners are probably the easiest — and
most common — event handlers to implement. You implement an action listener to define what
should be done when a user performs certain operation. An action event occurs, whenever an
action is performed by the user.
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Example of displaying image on the button:
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
What is a JButton?
The JButton class is a push-button implementation. When pressed, this component generates an
event and has a label. It can also have an image attached to it.
What are the AbstractButton class's subclasses?
JButton, JToggleButton, JCheckBox, and JRadioButton are the four types of buttons defined
by Swing. All of these classes are subclasses of AbstractButton, which extends JComponent.
As a result, all buttons have a set of characteristics in common.
What is the difference between JLabel and JButton?
A JButton is a push button that performs a specific action. JLabel is a component that
displays a short text string, an image, or both at the same time.
2. 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.
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,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);
}
}
3. JTextField
JTextField renders an editable single-line text box. A user can input non-formatted text in the
box. To initialize the text field, call its constructor and pass an optional integer parameter to it.
This parameter sets the width of the box measured by the number of columns. It does not limit
the number of characters that can be input in the box.
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
4. JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-
formatted text in the field. The constructor for JTextArea also expects two integer parameters
which define the height and width of the text-area in columns. It does not restrict the number of
characters that the user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea ("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with
default text initialized in the text-area.
import java.awt.FlowLayout;
import javax.swing.*;
frame.add(JArea);
frame.setVisible(true);
}
}
5. JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states – on/off. When
selected, the state is on and a small tick is displayed in the box.
Example:
It returns a checkbox with the label Show Help. Notice the second parameter in the constructor.
It is a boolean value that indicates the default state of the check-box. True means the check-box
is defaulted to on state.
import javax.swing.*;
frame.add(lbltext);
frame.add(boxjava);
frame.add(boxc);
frame.add(boxcplus);
frame.setVisible(true);
}
}
6. JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can select one choice
from the group.
Example:
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All three elements are
then added to the group. This ensures that only one option out of the available options in the
group can be selected at a time. The default selected option is set to Easy.
7. JComboBox
Example:
JTabbedPane is another very useful component that lets the user switch between tabs in an
application. This is a highly useful utility as it lets the user browse more content without
navigating to different pages.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JPanel());
tabbedPane.addTab("Tab 2", new JPanel());
9. JTables
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.
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
10. JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
JScrollPane( )
import java.awt.*;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Jscrollpane {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
frame.setContentPane(panel);
frame.setSize(500, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
JscrollPane (Component c)
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Jscrollpane {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextArea tArea = new JTextArea(10,10);
JScrollPane scrollPane = new JScrollPane(tArea);
panel.add(scrollPane);
frame.setContentPane(panel);
frame.setSize(500, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
11. JTree
JTree is a Swing component with which we can display hierarchical data. JTree is quite a
complex component. A JTree has a 'root node' which is the top-most parent for all nodes in the
tree. A node is an item in a tree. A node can have many children nodes. These children nodes
themselves can have further children nodes. If a node doesn't have any children node, it is called
a leaf node. The leaf node is displayed with a different visual indicator. The nodes with children
are displayed with a different visual indicator along with a visual 'handle' which can be used to
expand or collapse that node. Expanding a node displays the children and collapsing hides them.
The node is represented in Swing API as TreeNode which is an interface. The interface
MutableTreeNode extends this interface which represents a mutable node. Swing API provides
an implementation of this interface in the form of DefaultMutableTreeNode class.We will be
using the DefaultMutableTreeNode class to represent our node. This class is provided in the
Swing API and we can use it to represent our nodes. This class has a handy add() method which
takes in an instance of MutableTreeNode.
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 Creates a JTree with the specified TreeNode as its root, which displays the root node.
root)
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
12. JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.It doesn't have title bar. JPanel is a Swing’s
lightweight container which is used to group a set of components together. JPanel is a pretty
simple component which, normally, does not have a GUI (except when it is being set an opaque
background or has a visual border).
We frequently make a class that extends from JPanel in the following way:
public class Panel extends JPanel {
// RECOMMENDED:
JPanel Panel = new JPanel(new GridBagLayout());
We cannot specify a BoxLayout while establishing the panel since its constructor requires an
existing container. For instance:
// Exception
JPanel Panel = new JPanel(); // a FlowLayout manager is created by default
Panel.setLayout(new BoxLayout(Panel, BoxLayout.X_AXIS));
For the FlowLayout, BoxLayout, GridLayout, or SpringLayout layout managers, use the
add(Component) method.
Use the add(Component comp, Object constraints) method for the following layout managers:
CardLayout, GridBagLayout, or BorderLayout.
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}