Java如何为单选按钮创建ButtonGroup?

本示例说明如何创建一个ButtonGroup将单选按钮组件分组为一个组的。在此示例中,您还可以看到我们向单选按钮添加了一个动作监听器。

package org.nhooo.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonGroupDemo extends JFrame {
    public ButtonGroupDemo() {
        initializeUI();
    }

    private void initializeUI() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // 为我们的单选按钮创建一个动作监听器。
        ActionListener action = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JRadioButton button = (JRadioButton) e.getSource();
                System.out.println("You select button: " + button.getText());
            }
        };

        // 创建四个单选按钮并设置动作侦听器。
        JRadioButton button1 = new JRadioButton("One");
        button1.addActionListener(action);
        JRadioButton button2 = new JRadioButton("Two");
        button2.addActionListener(action);
        JRadioButton button3 = new JRadioButton("Three");
        button3.addActionListener(action);
        JRadioButton button4 = new JRadioButton("Four");
        button4.addActionListener(action);

        //创建一个ButtonGroup将单选按钮分组为一组。这个
        // 将确保在菜单上仅选择一项或一项收音机
        // 组。
        ButtonGroup group = new ButtonGroup();
        group.add(button1);
        group.add(button2);
        group.add(button3);
        group.add(button4);

        getContentPane().add(button1);
        getContentPane().add(button2);
        getContentPane().add(button3);
        getContentPane().add(button4);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ButtonGroupDemo().setVisible(true);
            }
        });
    }
}