Get selected JRadioButton from ButtonGroup

Complete source code below will show you, how to get selected JRadioButton from ButtonGroup.

*************************************************************************
COMPLETE SOURCE CODE FOR : GetSelectedJRadioButtonFromButtonGroup.java
*************************************************************************


import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.AbstractButton;

import java.awt.BorderLayout;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.util.Enumeration;

public class GetSelectedJRadioButtonFromButtonGroup implements ActionListener
{
//Create two radio button that will be put into a group
//Set start radio button selection to female
JRadioButton firstRadioButton=new JRadioButton("Female",true);
JRadioButton secondRadioButton=new JRadioButton("Male");

//Create a button with text ( What i select )
JButton button=new JButton("What i select");

//Create a window using JFrame with title ( Get selected JRadioButton from ButtonGroup)
JFrame frame=new JFrame("Get selected JRadioButton from ButtonGroup");

//Create a radio button group using ButtonGroup
ButtonGroup bg=new ButtonGroup();

public GetSelectedJRadioButtonFromButtonGroup()
{
//Add all radio button into created group
bg.add(firstRadioButton);
bg.add(secondRadioButton);

//Set JFrame layout to border layout
frame.setLayout(new BorderLayout());

//Create a panel that will be put radio button into it
JPanel panel=new JPanel();

//Add all created radio button into panel
panel.add(firstRadioButton);
panel.add(secondRadioButton);

//Add action listener to created button
button.addActionListener(this);

//Add panel and button into JFrame
frame.add(panel,BorderLayout.CENTER);
frame.add(button,BorderLayout.SOUTH);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(600,150);

//Make JFrame visible
frame.setVisible(true);
}

//Action for button
//Get selected JRadioButton from ButtonGroup
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
Enumeration<AbstractButton> allRadioButton=bg.getElements();

while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(frame,"You select : "+temp.getText());
}
}
}
}

public static void main(String[]args)
{
GetSelectedJRadioButtonFromButtonGroup gsjrbfbg=new GetSelectedJRadioButtonFromButtonGroup();
}
}



*************************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************************

RELAXING NATURE VIDEO