Get selected JRadioButton in Java

Description

The following code shows how to get selected JRadioButton.

Example


/*from ww  w .  ja v a2  s  . co  m*/
  
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;

import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Radio Buttons");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JPanel panel = new JPanel(new GridLayout(0, 1));
    Border border = BorderFactory.createTitledBorder("Options");
    panel.setBorder(border);
    
    final ButtonGroup group = new ButtonGroup();
    AbstractButton abstract1 = new JRadioButton("One");
    panel.add(abstract1);
    group.add(abstract1);
    AbstractButton abstract2 = new JRadioButton("Two");
    panel.add(abstract2);
    group.add(abstract2);
    AbstractButton abstract3 = new JRadioButton("Three");
    panel.add(abstract3);
    group.add(abstract3);
    AbstractButton abstract4 = new JRadioButton("Four");
    panel.add(abstract4);
    group.add(abstract4);
    AbstractButton abstract5 = new JRadioButton("Five");
    panel.add(abstract5);
    group.add(abstract5);
    ActionListener aListener = new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        Enumeration elements = group.getElements();
        while (elements.hasMoreElements()) {
          AbstractButton button = (AbstractButton) elements.nextElement();
          if (button.isSelected()) {
            System.out.println("The winner is: " + button.getText());
            break;
          }
        }
        group.setSelected(null, true);
      }
    };
    JButton button = new JButton("Show Selected");
    button.addActionListener(aListener);
    Container container = frame.getContentPane();
    container.add(panel, BorderLayout.CENTER);
    container.add(button, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Get selected JRadioButton in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer