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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2408689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:12:19  来源:igfitidea点击:

Unselecting RadioButtons in Java Swing

javaswingradio-button

提问by Thomas

When displaying a group of JRadioButtons, initially none of them is selected (unless you programmatically enforce that). I would like to be able to put buttons back into that state even after the user already selected one, i.e., none of the buttons should be selected.

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

However, using the usual suspects doesn't deliver the required effect: calling 'setSelected(false)' on each button doesn't work. Interestingly, it doeswork when the buttons are not put into a ButtonGroup - unfortunately, the latter is required for JRadioButtons to be mutually exclusive.

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

Also, using the setSelected(ButtonModel, boolean) - method of javax.swing.ButtonGroup doesn't do what I want.

此外,使用 setSelected(ButtonModel, boolean) - javax.swing.ButtonGroup 的方法并不能满足我的要求。

I've put together a small program to demonstrate the effect: two radio buttons and a JButton. Clicking the JButton should unselect the radio buttons so that the window looks exactly as it does when it first pops up.

我已经编写了一个小程序来演示效果:两个单选按钮和一个 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);
    }
}

Any ideas anyone? Thanks!

任何人的想法?谢谢!

采纳答案by Santhosh Kumar Tekuri

You can do buttonGroup.clearSelection().

你可以做到buttonGroup.clearSelection()

But this method is available only since Java 6.

但是此方法仅从 Java 6 开始可用。

回答by Ash

Try adding a third invisible button to the button group. When you want to "deselect", select the invisible one.

尝试向按钮组添加第三个不可见按钮。当你想“取消选择”时,选择不可见的。

回答by sateesh

The Javadoc of the class ButtonGroupitself gives some hint about how this can be achieved:

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

From the API doc of class ButtonGroup:
Initially, all buttons in the group are unselected. Once any button is selected, one button is always selected in the group.There is no way to turn a button programmatically to "off", in order to clear the button group. To give the appearance of "none selected", add an invisible radio button to the group and then programmatically select that button to turn off all the displayed radio buttons.

来自 class 的 API 文档ButtonGroup
最初,组中的所有按钮都未选中。一旦选择了任何一个按钮,组中的一个按钮总是被选中。没有办法以编程方式将按钮设置为“关闭”,以清除按钮组。要呈现“未选择”的外观,请向组中添加一个不可见的单选按钮,然后以编程方式选择该按钮以关闭所有显示的单选按钮。

回答by camickr

Or you can use Darryl's Select Button Groupwhich doesn't require you to use an "invisible button".

或者您可以使用 Darryl 的Select Button Group,它不需要您使用“隐形按钮”。

回答by user2205752

You can use setselected(false)method to unselect the previous selected button.

您可以使用setselected(false)method 取消选择上一个选定的按钮。

回答by user2572559

I don't know if this will help but have you tried to use doClick()method?

我不知道这是否会有所帮助,但您是否尝试过使用doClick()方法?

jRadioButtonYourObject.doClick();

Input - NONE

输入 - 无

Return- void

返回 - 无效

I had a similar problem and tried everything in this thread to no avail. So I took a look at all the methods of JRadioButton and found that method from JRadioButton's parent class.

我遇到了类似的问题,并尝试了此线程中的所有内容均无济于事。所以我查看了 JRadioButton 的所有方法,并从 JRadioButton 的父类中找到了该方法。

In my program, I had two radio button independent of each other and it was programed so that only one was selected.

在我的程序中,我有两个相互独立的单选按钮,它被编程为只选择一个。

After the user enters data and hits a button the program clears all text fields and areas and deselects the radio button. The doClick()did the job of deselecting the radio button for me; the method "performs a "click"."

用户输入数据并点击按钮后,程序会清除所有文本字段和区域并取消选择单选按钮。在doClick()没有取消对我的单选按钮的工作; 该方法“执行“点击”。

I know yours is different and you probably would have to program the doClick() method for every radio button that is selected.

我知道您的情况不同,您可能必须为每个选定的单选按钮编写 doClick() 方法。

http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html

http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html

search for doClick()

搜索 doClick()

回答by user1815823

When you want to deselect, select invisible. For that you add a third invisible button to the button group.

当您要取消选择时,请选择不可见。为此,您将第三个不可见按钮添加到按钮组。

回答by Tomá? Zálusky

In my case I use Jgoodies project to bind GUI components to Java model. The RadioButton component is bound to a field

就我而言,我使用 Jgoodies 项目将 GUI 组件绑定到 Java 模型。RadioButton 组件绑定到一个字段

class Model {
  private SomeJavaEnum field; // + getter, setter
}

In such case ButtonGroup.clearSelectiondoesn't work since the old value still retains in the model. Straightforward solution was to simply setField(null).

在这种情况下ButtonGroup.clearSelection不起作用,因为旧值仍然保留在模型中。直接的解决方案是简单地setField(null).

回答by Ar maj

Use this helper class SelectButtonGroup.javadirect link to the class source

使用这个助手类SelectButtonGroup.java直接链接到类source

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

public class SelectUnselected extends JPanel {
    private static String birdString = "Bird";
    private static String catString = "Cat";
    private static Integer selectedIndex = -1;
    private static AbstractButton hiddenButton = new JRadioButton(catString);
    private final static AbstractButton birdButton = new JRadioButton(birdString);
    private final static AbstractButton catButton = new JRadioButton(catString);
    //Group the radio buttons.
    private SelectButtonGroup group = new SelectButtonGroup();

public SelectUnselected() {
    super(new BorderLayout());

    //Create the radio buttons.
    hiddenButton.setVisible(false);
    hiddenButton.setSelected(true);

    group.add(birdButton);
    group.add(catButton);
    group.add(hiddenButton);


    ActionListener sendListener = e -> {
        checkSelectedRadioButten();
    };
    birdButton.addActionListener(sendListener);
    catButton.addActionListener(sendListener);
    hiddenButton.addActionListener(sendListener);



    //Put the radio buttons in a column in a panel.
    JPanel radioPanel = new JPanel(new GridLayout(0, 1));
    radioPanel.add(birdButton);
    radioPanel.add(catButton);

    add(radioPanel, BorderLayout.LINE_START);
    setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}

public void checkSelectedRadioButten(){

    System.out.println("selectedIndex = " + selectedIndex + "\ngroup.getSelectedButton() = " + group.getSelectedIndex());
    if(group.getSelectedIndex() == selectedIndex){
        hiddenButton.setSelected(true);
        selectedIndex = -1;
        System.out.println("getText = " + group.getSelectedButton().getText());
    }else{
        selectedIndex = group.getSelectedIndex();
        System.out.println("getText = " + group.getSelectedButton().getText());
    }
}

public static void main(String[] args) {
    JFrame frame = new JFrame("RadioButtonDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComponent newContentPane = new SelectUnselected();
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);

    }
}

回答by justDev7a3

You can use a click counter:

您可以使用点击计数器:

private ButtonGroup radioGroup = new javax.swing.ButtonGroup();
private JRadioButton jRadioBtn1 = new javax.swing.JRadioButton();
private int clickCount = 0;

private void jRadioBtn1Clicked(java.awt.event.MouseEvent evt) {                                             
    // Remove selection on a second click
    if (jRadioBtn1.isSelected()) {

        if (++clickCount % 2 == 0) {

            radioGroup.clearSelection();
        }
    }
}