getSelection() - Getting Selected Button

This section provides a tutorial example on how to use the getSelection() method to know which button is selected in a button group.

If there are many radio buttons in a button group, how do you find the one that is currently selected? One way is to use the getSelection() method of ButtonGroup class. Here is a sample program:

/* JRadioButtonAction.java
 * Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonAction implements ActionListener {
   ButtonGroup myGroup = null;
   JLabel myLebal = null;
   public static void main(String[] a) {
      JRadioButtonAction myTest = new JRadioButtonAction();
      myTest.createFrame();
   }
   public void createFrame() {
      JFrame f = new JFrame("My Radio Buttons");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS));
      myGroup = new ButtonGroup();
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(3,1));
      addOption(p,myGroup,"Red");
      addOption(p,myGroup,"Green");
      addOption(p,myGroup,"Blue");
      c.add(p);
      JButton b = new JButton("Select");
      b.addActionListener(this);
      c.add(b);
      myLebal = new JLabel("Please select",SwingConstants.CENTER);
      c.add(myLebal);
      f.pack();
      f.setVisible(true);
   }
   public void addOption(JPanel p, ButtonGroup g, String t) {
      JRadioButton b = new JRadioButton(t);
      b.setActionCommand(t);
      p.add(b);
      g.add(b);
   }
   public void actionPerformed(ActionEvent e) {
      ButtonModel b = myGroup.getSelection();
      String t = "Not selected";
      if (b!=null) t = b.getActionCommand();
      myLebal.setText(t);
   }
}

If you run this program, you will see none of the radio buttons is selected initially. If you click "Select", you will get the "Not selected" message. If you select any of the radio buttons, then click "Select", you will get the correct message:
JRadioButton Selected Button

Sample programs listed in this section have been tested with JDK 1.3.1 to 1.8.0.

Last update: 2014.

Table of Contents

 About This Book

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

JRadioButton - Swing Radio Button Class

 javax.swing.JRadioButton and Related Classes

 ActionListener, ChangeListener and ItemListener

getSelection() - Getting Selected Button

 JTextField - Swing Text Field Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 References

 PDF Printing Version