JRadioButton

This control is useful when we wish to represent a group of buttons in which only one can be selected at a time.

Program

xzx

 

 

 

Program Source

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

class Frame extends JFrame implements ItemListener{
 
    private JRadioButton jr1,jr2,jr3;
    private JLabel jl;
 
    Frame()
    {
        setTitle("JRadioButton with ItemListener");
        setLayout(new FlowLayout());
        setJRadioButton();
        setAction();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJRadioButton()
    {
        jr1 = new JRadioButton("A");
        add(jr1);
        jr2 = new JRadioButton("B");
        add(jr2);
        jr3 = new JRadioButton("C");
        add(jr3);
        jl = new JLabel("Select any option");
        add(jl);
    }
 
    private void setAction()
    {
        jr1.addItemListener(this);
        jr2.addItemListener(this);
        jr3.addItemListener(this);
    }
 
    public void itemStateChanged(ItemEvent eve)
    {
        if(jr1.isSelected())
        {
            jl.setText("A selected");
            if(jr2.isSelected())
            {
                jl.setText("A and B selected");
                if(jr3.isSelected())
                jl.setText("A,B and C selected");
            }
            else if(jr3.isSelected())
            {
                jl.setText("A and C selected");
            }
        }
        else if(jr2.isSelected())
        {
            jl.setText("B selected");
            if(jr3.isSelected())
            {
                jl.setText("B and C selected");
            }
        }
        else if(jr3.isSelected())
            jl.setText("C selected");          
        else
            jl.setText("Select any option");
    }
}

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

Leave a Comment