Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to add ItemListener to JCheckbox using Swing API in Java ?

Program to demonstrate how to apply event handling mechanism to JCheckBox Swing Components :

package com.hubberspot.awtSwing.example;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CheckBoxItemListener implements ItemListener
{
  JFrame frame;
  JCheckBox checkBoxArray[] = new JCheckBox[3];
  JTextField textField;
  JLabel label;
  JPanel panel;
  CheckBoxItemListener()
  {
    frame = new JFrame("JCheckBox Event Handling");
    frame.setLayout(new GridLayout(3,1));
    panel = new JPanel();
    checkBoxArray[0] = new JCheckBox("Java"); 
    checkBoxArray[1] = new JCheckBox("C++");
    checkBoxArray[2] = new JCheckBox("C");
    for(int i = 0; i<3; i++)
    {
       panel.add(checkBoxArray[i]);
       checkBoxArray[i].addItemListener(this);
    }
    textField = new JTextField(20);
    label = new JLabel("Select the Programming " +
         "Language you have used : ", JLabel.CENTER);
    frame.add(label);  
    frame.add(panel);   
    frame.add(textField);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public void itemStateChanged(ItemEvent ie)
  {
    String message="You have used: "; 
    for(int i=0; i<3; i++)
    {
     if(checkBoxArray[i].isSelected())
       message += checkBoxArray[i].getText() + "  ";
    }
    textField.setText(message);
  }
  public static void main(String[] args)
  {
    new CheckBoxItemListener();
  }
}
Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot