Get selected JRadioButton

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

***************************************************************************
COMPLETE SOURCE CODE FOR : GetSelectedJRadioButton.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 java.awt.BorderLayout;

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

public class GetSelectedJRadioButton 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 )
JFrame frame=new JFrame("Get selected JRadioButton");

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

//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(300,150);

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

//Action for button
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
if(firstRadioButton.isSelected())
{
JOptionPane.showMessageDialog(frame,"You select : "+firstRadioButton.getText());
}

else if(secondRadioButton.isSelected())
{
JOptionPane.showMessageDialog(frame,"You select : "+secondRadioButton.getText());
}
}
}

public static void main(String[]args)
{
GetSelectedJRadioButton gsjrb=new GetSelectedJRadioButton();
}
}


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

RELAXING NATURE VIDEO