Get last selected JRadioButton

Complete source code below will show you, how to get last selected JRadioButton when we click on other JRadioButton. I hope you will understand what i want to tell you, or you can try to compile and execute source code below.

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


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class GetLastSelectedJRadioButton implements ItemListener
{
JRadioButton jrd1=new JRadioButton("a");
JRadioButton jrd2=new JRadioButton("b");
JRadioButton jrd3=new JRadioButton("c");
JRadioButton jrd4=new JRadioButton("d");

JRadioButton last=null;

ButtonGroup bg=new ButtonGroup();

JFrame myFrame=new JFrame("Get last selected JRadioButton");

public GetLastSelectedJRadioButton()
{
jrd1.addItemListener(this);
jrd2.addItemListener(this);
jrd3.addItemListener(this);
jrd4.addItemListener(this);

bg.add(jrd1);
bg.add(jrd2);
bg.add(jrd3);
bg.add(jrd4);

myFrame.getContentPane().setLayout(new GridLayout(4,1));

myFrame.getContentPane().add(jrd1);
myFrame.getContentPane().add(jrd2);
myFrame.getContentPane().add(jrd3);
myFrame.getContentPane().add(jrd4);

myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400,400);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
}

public void itemStateChanged(ItemEvent event)
{
JRadioButton temp=(JRadioButton)event.getItem();

if(event.getStateChange()==ItemEvent.DESELECTED)
{
last=temp;
}
else if(event.getStateChange()==ItemEvent.SELECTED)
{
if(last!=null)
{
JOptionPane.showMessageDialog(myFrame,"LAST : "+last.getText(),"Last",JOptionPane.INFORMATION_MESSAGE);
}
}
}

public static void main(String[]args)
{
GetLastSelectedJRadioButton glsjrb=new GetLastSelectedJRadioButton();
}
}


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