Get selected JRadioButton in a ButtonGroup in Java
Description
The following code shows how to get selected JRadioButton in a ButtonGroup.
Example
import java.awt.FlowLayout;
import java.util.Enumeration;
/* www.jav a 2s. co m*/
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton button1 = new JRadioButton("Red");
JRadioButton button2 = new JRadioButton("Green");
JRadioButton button3 = new JRadioButton("Blue");
ButtonGroup colorButtonGroup = new ButtonGroup();
colorButtonGroup.add(button1);
colorButtonGroup.add(button2);
colorButtonGroup.add(button3);
button1.setSelected(true);
frame.add(new JLabel("Color:"));
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.pack();
frame.setVisible(true);
for (Enumeration e = colorButtonGroup.getElements(); e.hasMoreElements();) {
JRadioButton b = (JRadioButton) e.nextElement();
if (b.getModel() == colorButtonGroup.getSelection()) {
System.out.println(b.getText());
}
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »