Pin It

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 : 


 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot