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

新手上路,请多包涵

当显示一组 JRadioButton 时,最初没有一个被选中(除非您以编程方式强制执行)。即使用户已经选择了一个按钮,我也希望能够将按钮恢复到该状态,即不应选择任何按钮。

但是,使用通常的嫌疑人并不能达到所需的效果:在每个按钮上调用“setSelected(false)”是行不通的。有趣的是,当按钮未放入 ButtonGroup 时它 确实 有效 - 不幸的是,JRadioButton 需要后者才能相互排斥。

此外,使用 setSelected(ButtonModel, boolean) - 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);
    }
}

有什么想法吗?谢谢!

原文由 Thomas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

该类的 Javadoc ButtonGroup 本身给出了一些关于如何实现这一点的提示:

来自类的 API 文档 ButtonGroup

最初,组中的所有按钮都未被选中。选择任何按钮后,组中始终会选择一个按钮。无法以编程方式将按钮设置为“关闭”,以清除按钮组。 要给出“未选中”的外观,请向组中添加一个不可见的单选按钮,然后以编程方式选择该按钮以关闭所有显示的单选按钮。

原文由 sateesh 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题