New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL
See the Tutorial List

Java Swing Components and Containers

A component is an independent visual control and Java Swing Framework contains a large set of these 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
    • It inherits Component and Container of AWT.
    • It cannot be contained within other containers.
    • Heavyweight.
    • Example: JFrame, JDialog, JApplet
  2. Lightweight Containers
    • It inherits JComponent class.
    • It is a general purpose container.
    • It can be used to organize related components together.
    • Example: JPanel

Swing JButton

JButton class provides functionality of a button. It is used to create button component. JButton class has three constuctors,

Example of JButton

In this example, we are creating two buttons using Jbutton class and adding them into Jframe container.

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();
  }
}

swing button example

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

In this example, we are creating text field using JtextField class and adding into the jframe container.

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();
  }
}

jtextfield example

JCheckBox

The JcheckBox class is used to create chekbox in swing framework. In this example, we are creating three checkboxes to get user response.

JCheckBox(String str)
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();
  }
}

jcheckbox example

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

To create radio button in swing, we used jradiobutton class. It is used to get single user response at a time.

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();
 }
}

jradiobutton example

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

Lets create an example to add combobox to the jframe . Combo box is used to create a drop-down menu. See the below example.

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();
 }
}

jcombobox example

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();
    }
}

Output:

Background Color of a frame

JLabel

In Java, Swingtoolkit contains a JLabel Class. It is under package javax.swing.JLabel class. It is used for placing text in a box. Only Single line text is allowed and the text can not be changed directly.

Declaration

public class JLabel extends JComponent implements SwingConstants, Accessible

The JLabel Contains 4 constructors. They are as following:

1. JLabel()

2. JLabel(String s)

3. JLabel(Icon i)

4. JLabel(String s, Icon i, int horizontalAlignment)

Example:

  
import javax.swing.*;  
class SLabelDemo1  
{  
public static void main(String args[])  
{  
    JFrame label_f= new JFrame("studytonight ==> Label Demo");  
    JLabel label_l1,label_l2;  
    label_l1=new JLabel("Welcome to studytonight.com");  
    label_l1.setBounds(50,50, 200,30);  
    label_l2=new JLabel("How are You?");  
    label_l2.setBounds(50,100, 200,30);  
    label_f.add(label_l1); 
    label_f.add(label_l2);  
    label_f.setSize(300,300);  
    label_f.setLayout(null);  
    label_f.setVisible(true);  
    }  
} 
  

swing-jlabel-demo swing-jlabel-demo

JTextArea

In Java, Swing toolkit contains a JTextArea Class. It is under package javax.swing.JTextArea class. It is used for displaying multiple-line text.

Declaration

public class JTextArea extends JTextComponent

The JTextArea Contains 4 constructors. They are as following:

1. JTextArea()

2. JTextArea(String s)

3. JTextArea(int row, int column)

4. JTextArea(String s, int row, int column)

Example:

Lets take an example to create text area in swing. We are using JtextArea class to create text area and adding to Jframe container.

  
import javax.swing.*;  
public class STextAreaDemo1  
{  
    STextAreaDemo1()
  {  
        JFrame textArea_f= new JFrame();  
        JTextArea textArea_area=new JTextArea("Welcome to studytonight.com ");  
        textArea_area.setBounds(10,30, 200,200);  
        textArea_f.add(textArea_area);  
        textArea_f.setSize(400,400);  
        textArea_f.setLayout(null);  
        textArea_f.setVisible(true);  
        }  
public static void main(String args[])  
    {  
   new STextAreaDemo1();  
}
}
  

swing-textarea-demo swing-textarea-demo


JPasswordField

In Java, Swing toolkit contains a JPasswordField Class. It is under package javax.swing.JPasswordField class. It is specifically used for password and it can be edited.

Declaration

public class JPasswordField extends JTextField

The JPasswordFieldContains 4 constructors. They are as following:

1. JPasswordField()

2. JPasswordField(int columns)

3. JPasswordField(String text)

4. JPasswordField(String text, int columns)

Example:

To generate a password component, swing provides Jpasswordfield that takes user input in encrypted format.

  
import javax.swing.*;    
public class SPasswordFieldDemo1 
{  
    public static void main(String[] args) 
  {    
  JFrame passWord_f=new JFrame("studytonight ==> Password Field Demo");    
  JPasswordField passWord_value = new JPasswordField();   
  JLabel passWord_l1=new JLabel("Password ");    
        passWord_l1.setBounds(20,100, 100,30);    
        passWord_value.setBounds(100,100,100,30);    
        passWord_f.add(passWord_value);  
  passWord_f.add(passWord_l1);  
        passWord_f.setSize(300,300);    
        passWord_f.setLayout(null);    
        passWord_f.setVisible(true);     
  }  
} 
  

swing-password swing-password

JTable

In Java, Swing toolkit contains a JTable Class. It is under package javax.swing.JTable class. It used to draw a table to display data.

The JTableContains 2 constructors. They are as following:

1. JTable()

2. JTable(Object[][] rows, Object[] columns)

Example:

We are creating an example to create a table using Jtable class and then add it to the Jframe container.

  
import javax.swing.*;    
public class STableDemo1 
{    
    JFrame table_f;    
    STableDemo1(){    
    table_f=new JFrame();    
    String table_data[][]={ {"1001","Cherry"}, {"1002","Candy"}, {"1003","Coco"}};    
    String table_column[]={"SID","SNAME"};         
    JTable table_jt=new JTable(table_data,table_column);    
    table_jt.setBounds(30,40,200,300);          
    JScrollPane table_sp=new JScrollPane(table_jt);    
    table_f.add(table_sp);          
    table_f.setSize(300,400);    
    table_f.setVisible(true);    
}     
public static void main(String[] args) 
{    
    new STableDemo1();    
}    
}  
  

swing-table swing-table

JList

In Java, Swing toolkit contains a JList Class. It is under package javax.swing.JList class. It is used to represent a list of items together. One or more than one item can be selected from the list.

Declaration

public class JList extends JComponent implements Scrollable, Accessible

The JListContains 3 constructors. They are as following:

1. JList()

2. JList(ary[] listData)

3. JList(ListModel<ary> dataModel)

Example:

In this example, we are creating a list of items using Jlist class. this list is used to show the items in a list format and get user input from the list of items. See the below example.

  
import javax.swing.*;  
public class SListDemo  
{  
     SListDemo()
  {  
        JFrame list_f= new JFrame();  
        DefaultListModel<String> list_l1 = new DefaultListModel<>();  
        list_l1.addElement("Red");  
        list_l1.addElement("Pink");  
        list_l1.addElement("Blue");  
        list_l1.addElement("Black");  
        JList<String> list1 = new JList<>(list_l1);  
        list1.setBounds(100,100, 75,75);  
        list_f.add(list1);  
        list_f.setSize(400,400);  
        list_f.setLayout(null);  
        list_f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
  new SListDemo();  
    }
}
  

swing-list swing-list