Swing JRadioButton : Class



package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class JRadioButtonDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JRadioButtonDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(300, 300);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("JRadio Demo", JLabel.CENTER);
    msgLabel = new JLabel("Empty Selection", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JRadioButtonDemo radioDemo = new JRadioButtonDemo();
    radioDemo.showRadioButtonDemo();
  }

  private void showRadioButtonDemo() {

    JRadioButton radioHindi = new JRadioButton("Hindi");
    JRadioButton radioEnglish = new JRadioButton("English");
    JRadioButton radioTamil = new JRadioButton("Tamil");

    radioHindi.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        msgLabel.setText("Hindi : Selected");
      }
    });

    radioEnglish.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        msgLabel.setText("English : Selected");
      }
    });

    radioTamil.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        msgLabel.setText("Tamil : Selected");
      }
    });

    ButtonGroup radioGroup = new ButtonGroup();
    radioGroup.add(radioHindi);
    radioGroup.add(radioEnglish);
    radioGroup.add(radioTamil);

    mainPanel.add(radioHindi);
    mainPanel.add(radioEnglish);
    mainPanel.add(radioTamil);

    mainFrame.setVisible(true);
  }
}

Output :

Swing Radio Button