Unselecting RadioButtons in Java Swing
Asked Answered
I

11

40

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.

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

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

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.

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!

Inexpungible answered 9/3, 2010 at 11:43 Comment(1)
An example using key bindings is shown here.Antin
S
64

You can do buttonGroup.clearSelection().

But this method is available only since Java 6.

Sable answered 12/3, 2010 at 9:1 Comment(1)
Awesome! That explains why the Javadoc for ButtonGroup removed the part about the invisible RadioButton... (Now, if only they had added a part about clearSelection ;-))Inexpungible
C
7

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

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.

Convoy answered 9/3, 2010 at 11:56 Comment(2)
Oh my... I thought something was strange, as I had read through the API documentation before. Now, get this: turns out the part you quoted has been removed from the API documentation with Java 6! See here for a comparison: java.sun.com/j2se/1.5.0/docs/api/javax/swing/ButtonGroup.html (Java 5) and java.sun.com/javase/6/docs/api/javax/swing/ButtonGroup.html (Java 6). No wonder I wasn't able to find anything in the documentation...Inexpungible
@Inexpungible - I agree. Nonsense. Bleh.Bullfrog
B
4

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

Byelaw answered 9/3, 2010 at 11:56 Comment(0)
J
4

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();
        }
    }
}   
Joappa answered 15/10, 2016 at 4:55 Comment(0)
I
3

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

Intendment answered 9/3, 2010 at 16:52 Comment(0)
M
1

You can use your own ButtonGroup (1), or use modified instance (2), like this: ONLY SINCE 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);
            }
        };

take from https://blog.frankel.ch/unselect-all-toggle-buttons-of-a-group/

Markus answered 24/11, 2021 at 13:29 Comment(0)
D
0

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

Dhammapada answered 24/3, 2013 at 23:33 Comment(1)
As I said in my question (second paragraph), that did not work for me. Could you provide a code sample, please, to demonstrate what you mean?Inexpungible
S
0

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

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.

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"."

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

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

search for doClick()

Supersede answered 11/7, 2013 at 13:10 Comment(1)
Have you tried to use doClick() method? [..] I had a similar problem and tried everything in this thread to no avail. - The answer I selected as correct works for me.Inexpungible
A
0

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

Actinozoan answered 21/8, 2013 at 5:3 Comment(1)
See sateesh's answer, and also camickr's.Inexpungible
B
0

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

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

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

Biak answered 22/9, 2014 at 11:12 Comment(0)
F
0

Use this helper class SelectButtonGroup.java direct link to the class 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);

    }
}
Florencio answered 3/10, 2016 at 0:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.