JCheckBox(Select any one option)

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.

setSelected () :

This method is only one box in the group may be selected at a time.

Program

jhhj

 

 

 

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 option");
        add(jl);
    }
   
    private void setAction()
    {
        cb1.addItemListener(this);
        cb2.addItemListener(this);
    }
   
    public void itemStateChanged(ItemEvent eve)
    {
        if(cb2.isSelected())
        {
            jl.setText(cb2.getText() + " selected");
            cb1.setSelected(false);
        }
        else if(cb1.isSelected())
        {
            jl.setText(cb1.getText() + " selected");
            cb2.setSelected(false);
        }
        else
            jl.setText("Select any one option");
    }
}

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

Leave a Comment