在 Java Swing 中取消选择单选按钮

2022-09-01 03:01:20

显示一组 JRadioButton 时,最初不会选择任何一个(除非您以编程方式强制执行)。我希望即使在用户已经选择了按钮之后,也能够将按钮放回该状态,即,不应选择任何按钮。

但是,使用通常的可疑指标并不能提供所需的效果:在每个按钮上调用“setSelected(false)”不起作用。有趣的是,当按钮没有放入ButtonGroup时,它确实有效 - 不幸的是,后者是JRadioButtons相互排斥所必需的。

另外,使用 setSelected(ButtonModel,布尔值) - javax.swing.ButtonGroup 的方法不能做我想要的。

我整理了一个小程序来演示效果:两个单选按钮和一个JButton。单击 JButton 应取消选择单选按钮,以便窗口看起来与首次弹出时完全相同。

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

/**
 * This class creates two radio buttons and a JButton. Initially, none
 * of the radio buttons is selected. Clicking on the JButton should
 * always return the radio buttons into that initial state, i.e.,
 * should disable both radio buttons.
 */
public class RadioTest implements ActionListener {
    /* create two radio buttons and a group */
    private JRadioButton button1 = new JRadioButton("button1");
    private JRadioButton button2 = new JRadioButton("button2");
    private ButtonGroup group = new ButtonGroup();

    /* clicking this button should unselect both button1 and button2 */
    private JButton unselectRadio = new JButton("Unselect radio buttons.");

    /* In the constructor, set up the group and event listening */
    public RadioTest() {
        /* put the radio buttons in a group so they become mutually
         * exclusive -- without this, unselecting actually works! */
        group.add(button1);
        group.add(button2);

        /* listen to clicks on 'unselectRadio' button */
        unselectRadio.addActionListener(this);
    }

    /* called when 'unselectRadio' is clicked */
    public void actionPerformed(ActionEvent e) {
        /* variant1: disable both buttons directly.
         * ...doesn't work */
        button1.setSelected(false);
        button2.setSelected(false);

        /* variant2: disable the selection via the button group.
         * ...doesn't work either */
        group.setSelected(group.getSelection(), false);
    }

    /* Test: create a JFrame which displays the two radio buttons and
     * the unselect-button */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        RadioTest test = new RadioTest();

        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(3,1));
        contentPane.add(test.button1);
        contentPane.add(test.button2);
        contentPane.add(test.unselectRadio);

        frame.setSize(400, 400);
        frame.setVisible(true);
    }
}

任何人的任何想法?谢谢!


答案 1

你可以做 buttonGroup.clearSelection()

但这种方法仅在 Java 6 之后才可用。


答案 2

该类本身的 Javadoc 给出了一些有关如何实现此目的的提示:ButtonGroup

从类的API文档:
最初,组中的所有按钮都未选中。选择任何按钮后,始终在组中选择一个按钮。无法以编程方式将按钮设置为“关闭”,以便清除按钮组。若要使外观显示为“未选择”,请向组中添加一个不可见的单选按钮,然后以编程方式选择该按钮以关闭所有显示的单选按钮。 ButtonGroup