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:

 * Copyright (c) 1997-2024 All Rights Reserved.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonAction implements ActionListener {
   ButtonGroup myGroup = null;
   JLabel myLabel = null;
   public static void main(String[] a) {
      JRadioButtonAction myTest = new JRadioButtonAction();
   public void createFrame() {
      JFrame f = new JFrame("My Radio Buttons");
      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));
      JButton b = new JButton("Select");
      myLabel = new JLabel("Please select",SwingConstants.CENTER);
   public void addOption(JPanel p, ButtonGroup g, String t) {
      JRadioButton b = new JRadioButton(t);
   public void actionPerformed(ActionEvent e) {
      ButtonModel b = myGroup.getSelection();
      String t = "Not selected";
      if (b!=null) t = b.getActionCommand();

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
JRadioButton Selected Button

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JCheckBox - Swing Check Box 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

 JComboBox - Swing Combo Box 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

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials


 Full Version in PDF/EPUB