Java: Get Selected JRadioButton From ButtonGroup

(4 votes, average: 5.00 out of 5)
 Loading ...

The easiest and best way to get which JRadioButton got selected is to place them in a ButtonGroup object. This way, a group of JRadioButtons can be isolated from other group(s) of JRadioButtons and can easily be accessed.

The method below does the trick.

1
2
3
4
5
6
7
8
9
public static JRadioButton getSelection(ButtonGroup group) {
	for (Enumeration e=group.getElements(); e.hasMoreElements(); ) {
	   JRadioButton b = (JRadioButton)e.nextElement();
	   if (b.getModel() == group.getSelection()) {
	       return b;
	   }
	}
	return null;
}

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails