JCheckBox

The JCheckBox class provides the functionality of a check box. When the user selects or deselects a check box, an ItemEvent is generated. You canobtain a reference to the JCheckBox that generated the event by calling getItem( ) on the ItemEvent passed to the itemStateChanged( ) method defined by ItemListener. The easiest way to determine the selected state of a check box is to call isSelected( ) on the JCheckBox instance.

The getText returns the text of the corresponding check box.

Program

czcxc

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import java.awt.FlowLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

class Frame extends JFrame implements ItemListener{
   
    private JCheckBox cb1,cb2;
    private JLabel jl;
   
    Frame()
    {
        setTitle("JCheckBox with ItemListener");
        setLayout(new FlowLayout());
        setJCheckBox();
        setAction();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
   
    private void setJCheckBox()
    {
        cb1 = new JCheckBox("A");
        add(cb1);
        cb2 = new JCheckBox("B");
        add(cb2);
        jl = new JLabel("Select any one or multiple option");
        add(jl);
    }
   
    private void setAction()
    {
        cb1.addItemListener(this);
        cb2.addItemListener(this);
    }
   
    public void itemStateChanged(ItemEvent eve)
    {
        if(cb1.isSelected())
        {
            jl.setText(cb1.getText() + " selected");
            if(cb2.isSelected())
            {
                jl.setText(cb1.getText()+" and "+cb2.getText()+" selected");
            }
        }
        else if(cb2.isSelected())
            jl.setText(cb2.getText() + " selected");
        else
            jl.setText("Select any one or multiple option");
    }
}

public class Javaapp {
   
    public static void main(String[] args) {
        
       Frame frame = new Frame();
    }
}

Leave a Comment