Java Swing Tutorials - Herong's Tutorial Examples - v4.31, by Herong Yang
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) 1997-2018 HerongYang.com. 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(); 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); myLabel = new JLabel("Please select",SwingConstants.CENTER); c.add(myLabel); 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(); myLabel.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:
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
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
JEditorPane - The Editor Pane Class
SwingWorker - The Background Task Worker
AWT (Abstract Windows Toolkit)