[an error occurred while processing this directive]

Selecting a Radio Button component in Java


In this section, you will learn how to set the radio buttons in a group so that only one can be selected at a time.

This program shows five radio buttons with labeled by "First", "Second", "Third", "Fourth" and "Fifth". This program also show a label which contains the text "Roseindia.net" but when you click on any radio button from a ButtonGroup the text of the selected radio button is shown on the label and a message box will be shown with message holds the selected radio button label. This is done through the generating event for the different-different radio buttons. Following are the screen shots for the result of the given program:

Radio Buttons without selection

Frame with a message dialog box when you select the second radio button

For this purposes, there are some APIs or methods have been used as follows:

This is the method of the ActionEvent class which returns the source title in string of the generated event.

Here is the code of the program:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SelectRadioButton{
  JLabel label;
  public static void main(String[] args){
    SelectRadioButton sr = new SelectRadioButton();

  public SelectRadioButton(){
    JFrame frame = new JFrame("Radio button selection");
    JRadioButton first = new JRadioButton("First");
    JRadioButton second = new JRadioButton("Second");
    JRadioButton third = new JRadioButton("Third");
    JRadioButton fourth = new JRadioButton("Fourth");
    JRadioButton fifth = new JRadioButton("Fifth");
    JPanel panel = new JPanel();
    ButtonGroup bg = new ButtonGroup();
    first.addActionListener(new MyAction());
    second.addActionListener(new MyAction());
    third.addActionListener(new MyAction());
    fourth.addActionListener(new MyAction());
    fifth.addActionListener(new MyAction());
    label = new JLabel("Roseindia.net");
    frame.add(panel, BorderLayout.NORTH);
    frame.add(label, BorderLayout.CENTER);

  public class MyAction implements ActionListener{
    public void actionPerformed(ActionEvent e){
      JOptionPane.showMessageDialog(null,"This is the " + e.getActionCommand() 
" radio button."

Download this example.


[an error occurred while processing this directive]