Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

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) 2002 by Dr. Herong Yang, http://www.herongyang.com/
 */
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, 1.4.1, 1.5.0, and 1.6.0.

Last update: 2009.

Sections in This Chapter

javax.swing.JRadioButton and Related Classes

ActionListener, ChangeListener and ItemListener

getSelection() - Getting Selected Button

Dr. Herong Yang, updated in 2009
getSelection() - Getting Selected Button