Java Swing
Swing Framework contains a set of classes that provides more powerful and flexible GUI
components than those of AWT. Swing provides the look and feel of modern Java GUI. Swing
library is an official Java GUI tool kit released by Sun Microsystems. It is used to create
graphical user interface with Java.
Swing classes are defined in javax.swing package and its sub-packages.
Main Features of Swing Toolkit
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
Swing and JFC
JFC is an abbreviation for Java Foundation classes, which encompass a group of features for
building Graphical User Interfaces(GUI) and adding rich graphical functionalities and
interactivity to Java applications. Java Swing is a part of Java Foundation Classes (JFC).
Features of JFC
Swing GUI components.
Look and Feel support.
Java 2D.
AWT and Swing Hierarchy
Introduction to Swing Classes
JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The
component which is added to the Frame, is refered as its Content.
JWindow : This is Swing's version of Window and has descended directly from Window class.
Like Window it uses BorderLayout by default.
JLabel : JLabel has descended from JComponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows an icon, string
or both associated with a button.
JTextField : JTextFields allow editing of a single line of text.
Creating a JFrame
There are two ways to create a JFrame Window.
1. By instantiating JFrame class.
2. By extending JFrame class.
Creating JFrame window by Instantiating JFrame class
import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class First
{
JFrame jf;
public First() {
jf = new JFrame("MyWindow"); //Creating a JFrame with
name MyWindow
JButton btn = new JButton("Say Hello");//Creating a Button
named Say Hello
jf.add(btn); //adding button to frame
jf.setLayout(new FlowLayout()); //setting layout using
FlowLayout object
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting
close operation.
jf.setSize(400, 400); //setting size
jf.setVisible(true); //setting frame
visibility
}
public static void main(String[] args)
{
new First();
}
}
Creating JFrame window by extending JFrame class
import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow"); //setting title of frame as MyWindow
JLabel lb = new JLabel("Welcome to My Second
Window");//Creating a label named Welcome to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using
FlowLayout object.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting
close operation.
setSize(400, 400); //setting size
setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new Second();
}
}
Points To Remember
1. Import the javax.swing and java.awt package to use the classes and methods of Swing.
2. While creating a frame (either by instantiating or extending Frame class), following two
attributes are must for visibility of the frame:
3. setSize(int width, int height);
setVisible(true);
4. When you create objects of other components like Buttons, TextFields, etc. Then you
need to add it to the frame by using the method - add(Component's Object);
5. You can add the following method also for resizing the frame - setResizable(true);
Java Swing Components and Containers
A component is an independent visual control. Swing Framework contains a large set of
components which provide rich functionalities and allow high level of customization. They all
are derived from JComponent class. All these components are lightweight components. This
class provides some common functionality like pluggable look and feel, support for accessibility,
drag and drop, layout, etc.
A container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types:
1. Top level Containers
o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel
JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
JButton(String str, Icon ic)
It allows a button to be created using icon, a string or both. JButton supports ActionEvent.
When a button is pressed an ActionEvent is generated.
Example using JButton
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close
operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JTextField
JTextField is used for taking input of single line of text. It is most widely used text component.
It has three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.
Example using JTextField
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20);//creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for
JCheckBox,
JCheckBox(String str)
Example using JCheckBox
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}
JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton class
is used to create a radio button in Frames. Following is the constructor for JRadioButton,
JRadioButton(String str)
Example using JRadioButton
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("B"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("C"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("none");
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}
JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is used to
create a combo box in Swing. Following is the constructor for JComboBox,
JComboBox(String arr[])
Example using JComboBox
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of
name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}
A program to change background color of a frame (Using Action Event)
import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
import java.awt.event.*; //importing event package
//For an event to occur upon clicking the button, ActionListener interface
should be implemented
class StColor extends JFrame implements ActionListener{
JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;
StColor(){
frame = new JFrame("COLORS");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel(); //Creating a panel which is a container and will
hold all the buttons
panel.setSize(100, 50);
b1 = new JButton("BLUE"); //Creating a button named BLUE
b1.addActionListener(this); //Registering the button with the listener
b2 = new JButton("RED"); //Creating a button named RED
b2.addActionListener(this); //Registering the button with the listener
b3 = new JButton("CYAN");//Creating a button named CYAN
b3.addActionListener(this);//Registering the button with the listener
b4 = new JButton("PINK"); //Creating a button named PINK
b4.addActionListener(this); //Registering the button with the listener
b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA
b5.addActionListener(this); //Registering the button with the listener
//Adding buttons to the Panel
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);
frame.getContentPane().add(panel); //adding panel to the frame
frame.setSize(500,300);
frame.setVisible(true);
frame.setLayout(new FlowLayout());
}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {
//This method returns an object of the button on which the Event-
Pressing of button initially occurred
Object see = e.getSource();
if(see ==(b1)){ //Checking if the object returned is of button1
frame.getContentPane().setBackground(java.awt.Color.blue); //changing
the panel color to blue
}
if(see == b2){ //Checking if the object returned is of button2
frame.getContentPane().setBackground(java.awt.Color.red);
//changing the panel color to red
}
if(see == b3){ //Checking if the object returned is of button3
frame.getContentPane().setBackground(java.awt.Color.cyan);//changing
the panel color to cyan
}
if(see == b4){ //Checking if the object returned is of button4
frame.getContentPane().setBackground(java.awt.Color.pink);
//changing the panel color to pink
}
if(see == b5){ //Checking if the object returned is of button5
frame.getContentPane().setBackground(java.awt.Color.magenta);
//changing the panel color to magenta
}
}
}
class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}
Ouput:
Java Reflection API
Reflection means ability of a software to analyze itself. In Java, Reflection API provides facility
to analyze and change runtime behaviour of a Class, at runtime.
For example, using reflection at the runtime you can determine what method, field, constructor
or modifers a class supports.
What is reflect package?
java.lang.reflect package encapsulates several important interfaces and classes. These
classes and interface define methods which are used for reflection.
Some Important Classes of java.lang.reflect package
Class What it does ?
Array allow you to dynamically create and manipulate arrays
Constructor gives information about constructor of a class
Field provide information about field
Method provide information about method
Modifier provide information about class and member access modifier
Proxy supports dynamic proxy classes
Apart from these classes java.lang.Class is another very important class used in Reflection
API.
Uses of Reflection
Developing IDE
Debugging and Test tools
Loading drivers and providing dynamic information
Disadvantages of Reflection
Low performance
Security risk
Violation of Oops concept
Java java.lang.Class class
Class is a final class in java.lang package which extends Object class. Instance of this class
represents classes and interfaces in a running Java application. It is used to analyze and change
dynamic behaviour of a class at runtime.
Some Important Methods of java.lang.Class class
This class defines several methods using which we can get information about methods,
constructors, modifiers and members of a class at runtime.
forName()
This method takes fully qualified name of classes or interface as its argument and returns
instance of the class assocaited with it. Syntax
static Class< ?> forName(String className)
Example using forName() method
class Student{}
class Test
{
public static void main(String args[])
{
Class c = Class.forName("Student");
System.out.println(c.getName());
}
}
Student
getConstructors() and getDeclaredConstructors()
getConstructors() method returns array of Constructors object that represent all the public
constructors of the invoking object. Remember, this method only returns public constructors. If
you want to see all the declared constructors of a class then use getDeclaredConstructors().
Following is the general syntax of both,
Constructor< ?>[] getConstructors();
Constructor< ?>[] getDeclaredConstructors();
Example using getConstructors() and getDeclaredConstructors() method
import java.lang.reflect.*;
class Student
{
public Student(){}
public Student(String name){}
}
class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Constructor< Student>[] ct = c.getConstructors();
for(int i=0; i< ct.length; i++)
{ System.out.println(ct[i]); }
Constructor< Student>[] cdt = c.getDeclaredConstructors();
for(int i=0;i< cdt.length;i++)
{ System.out.println(cdt[i]);}
}
catch(Exception e)
{ e.printStackTrace();}
}
}
public Student() public Student() Student(java.lang.String)
getMethods() and getDeclaredMethods()
getMethods() method returns array of Method object that reflect all the public method of
invoking object. getDeclaredMethods() returns only the declared methods of the invoking
class object. Syntax for both is following,
Method< ?>[] getMethods();
Method< ?>[] getDeclaredMethods();
Example using getDeclaredMethods() method
import java.lang.reflect.*;
class Student
{
public void show(){}
void display(){}
}
class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Method md[] = c.getDeclaredMethods();
for(int i=0; i< md.length; i++ )
{ System.out.println(md[i]); }
}
catch(Exception e)
{ e.printStackTrace();}
}
}
public void Student.show() void Student.display()
getFields() and getDeclaredFields()
getFields() returns an array containing Field objects reflecting all the accessible public
members of the class or interface represented by this Class object. getDeclaredFields()
returns array of Field objects reflecting all the fields declared by the class or interface
represented by this Class object.
Field< ?>[] getFields();
Field< ?>[] getDeclaredFields();
Example using getFields() and getDeclaredFields() method
import java.lang.reflect.*;
class Student
{
public String name;
int roll;
}
class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Field ff[] = c.getFields();
for(int i=0; i< ff.length; i++)
{ System.out.println(ff[i]); }
Field f[] = c.getDeclaredFields();
for(int i=0;i< f.length; i++)
{ System.out.println(f[i]); }
}
catch(Exception e)
{ e.printStackTrace();}
}
}
public java.lang.String Student.name public java.lang.String Student.name int Student.roll