How to determine which radio button is selected in a button group in java?

Many times we add multiple JRadioButtons and if we want to have only one selection among those radio buttons we use ButtonGroup class. When we use ButtonGroup then user only selects one Radio Button at time. When we try to get currently selected ButtonGroup , then button group doesn't return button but it returns button model. But button group maintains list of button to which we can compare the button model and get currently selected JRadioButton.

Following function demonstrates the code for getting currently selected JRadioButton.

public static JRadioButton getSelectedRadio(ButtonGroup group) {
for (Enumeration eRadio=group.getElements(); eRadio.hasMoreElements(); ) {
//Iterating over the Radio Buttons
JRadioButton radioButton = (JRadioButton)eRadio.nextElement();
//Comparing radioButtons model with groups selection
if (radioButton.getModel() == group.getSelection()) {
return radioButton;
return null;
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment