【问题标题】:Unselecting RadioButtons in Java Swing在 Java Swing 中取消选择单选按钮
【发布时间】:2011-01-25 09:45:22
【问题描述】:

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

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

另外,使用 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);
    }
}

有什么想法吗?谢谢!

【问题讨论】:

  • 一个使用键绑定的例子显示在here

标签: java swing radio-button


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      你可以buttonGroup.clearSelection()

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

      【讨论】:

      • 太棒了!这就解释了为什么 ButtonGroup 的 Javadoc 删除了关于不可见 RadioButton 的部分......(现在,如果他们添加关于 clearSelection 的部分;-))
      【解决方案5】:

      您可以使用setselected(false)方法取消选择之前选择的按钮。

      【讨论】:

      • 正如我在问题(第二段)中所说,这对我不起作用。您能否提供一个代码示例来说明您的意思?
      【解决方案6】:

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

      jRadioButtonYourObject.doClick();
      

      输入 - 无

      返回-无效

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

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

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

      我知道你的不同,你可能需要为每个选中的单选按钮编写 doClick() 方法。

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

      搜索doClick()

      【讨论】:

      • 你试过doClick()方法吗? [..] 我遇到了类似的问题,并尝试了该线程中的所有方法均无济于事。 - 我选择正确的答案对我有用。
      【解决方案7】:

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

      【讨论】:

      • 见 sateesh 的回答,还有 camickr 的。
      【解决方案8】:

      在我的例子中,我使用 Jgoodies 项目将 GUI 组件绑定到 Java 模型。 RadioButton 组件绑定到一个字段

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

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

      【讨论】:

        【解决方案9】:

        使用这个帮助类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);
        
            }
        }
        

        【讨论】:

          【解决方案10】:

          您可以使用点击计数器:

          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();
                  }
              }
          }   
          

          【讨论】:

            【解决方案11】:

            您可以使用自己的 ButtonGroup (1),或使用修改后的实例 (2),如下所示: 仅自 JAVA 6 起:

            (1) public class NoneSelectedButtonGroup extends ButtonGroup {
              @Override
              public void setSelected(ButtonModel model, boolean selected) {
                if (selected) {
                  super.setSelected(model, selected);
                } else {
                  clearSelection();
                }
              }
            }
            
            (2) ButtonGroup chGroup = new ButtonGroup() {
                        @Override
                        public void setSelected(ButtonModel m, boolean b) {
                            if (!b) clearSelection();
                            else
                                super.setSelected(m, b);
                        }
                    };
            

            取自https://blog.frankel.ch/unselect-all-toggle-buttons-of-a-group/

            【讨论】:

              猜你喜欢
              • 2012-02-21
              • 2011-07-17
              • 2013-10-01
              • 1970-01-01
              • 2015-07-01
              • 1970-01-01
              • 2015-02-27
              • 1970-01-01
              相关资源
              最近更新 更多