开发者

Uncheck all checkboxes added as a group

I have 4 checkboxes added开发者_开发技巧 as a group so that I will be able to select only one checkbox. But if I select one of them and now want to uncheck all of them in a group, I am unable to do that. Any one has idea how can I do that?


The behavior you're asking about is half-check-box and half-radio-button, and here's how you do it right: Make it a group of five radio buttons, the first of which (or last) basically says 'none of the other options'.


Building on @trashgod's answer, here is a runnable example of code where a JButton is hooked up to clear the selection from a group of JRadioButton objects using ButtonGroup.clearSelection():

public class ClearableRadioButtons extends JFrame {

    public ClearableRadioButtons() {
        JPanel content = new JPanel();
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));

        final ButtonGroup group = new ButtonGroup();
        for (int i = 1; i < 10; i++) {
            JRadioButton nextButton = new JRadioButton("Button " + i);
            group.add(nextButton);
            content.add(nextButton);
        }
        content.add(new JButton(new AbstractAction("Clear") {
            public void actionPerformed(ActionEvent arg0) {
                // This is the one line you really care about:
                group.clearSelection();
            } 
        }));

        setLayout(new BorderLayout());
        add(content, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ClearableRadioButtons();
            }
        });
    }
}

Note that this code will work equally well if you replace all the instances of JRadioButton with JCheckBox. However, this is not recommended, because the standard way to indicate that only one thing can be chosen is to use radio buttons rather than checkboxes. If the user sees checkboxes, users will generally expect to be allowed to select more than one, and they will become annoyed when selecting one of the checkboxes causes other ones to become unselected.

If you really don't like the way JRadioButton buttons look, then I suggest playing with your Swing look-and-feel to change all of your checkboxes and radio buttons in your application until you are happy with the result.


You can use clearSelection(), which "Clears the selection such that none of the buttons in the ButtonGroup are selected."

As an aside, using JRadioButton in a single-selection group might be less confusing than check boxes.

Addendum: @Joe Carnahan and @Chris suggested clear ways to make the "no selection" choice explicit. You might also look at Chapter 10 of the Java Look and Feel Design Guidelines, which discusses independent v. exclusive choice in connection with toggle buttons generally.


--[EDIT]--
I made a mistake, I answered this thinking it was about a C# .NET project of another question I was reading. Vote to close it if you will, but read this note before choosing to downvote.
--[/EDIT]--

For what you said afterwards, you wand radioboxes that could act as checkboxes (re-clicking the same should un-check it). For that, you could use radiobuttons and add an option named "none" that will act as if no option was select, or put a "clean" button that de-selects every radiobutton.

Or if you REALLY want to do this, you could use CheckBox_CheckedChanged handler, which is triggered everytime a the checkbox is checked OR unchecked, so you'd have to see if the checkbox is checked inside the handler. The code inside the handler Should look like this:

If (CheckBox1.Checked)
{
    CheckBox2.Checked = False;
    CheckBox3.Checked = False;
    CheckBox4.Checked = False;
    CheckBox5.Checked = False;
}
// same for other checkboxes

Or make a function that takes the currently checked checkbox and unchecks the others, and put it inside each handler, each sending the desired checkbox.

But I highly sugest you to choose one of the first solutions I gave..


You are describing the behavior of a RadioButton, which is a selection group which only allows one option to be selected at a given time; support for this is built into Swing.


EDIT: I misread the question.

To deselect all checkboxes you can iterate the Containers children or, easier, use ButtonGroup.getElements() to enumerate the buttons in a particular group.


It's an old discussion ... but I had exactly the same problem and did not want a workaround solution as adding a "clear selection button". So, I wrote my own ButtonGroup that solves the original question (a button can be deselected, leaving the group with no button selected). It also adds the ability to be observed by a java.util.Observer that will be informed every time the selected button changes.

Here is the code:

package net.yapbam.gui.util;

import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.io.Serializable;

import javax.swing.JToggleButton;

/**
 * This class is, like javax.swing.ButtonGroup, used to create a multiple-exclusion scope for
 * a set of buttons. Creating a set of buttons with the same <code>ButtonGroup</code> object means that
 * turning "on" one of those buttons turns off all other buttons in the group.
 * <p>
 * The main difference of this group with the swing one is that you can deselected buttons by clicking on them
 * and have a group without no selected button.<br>
 * Another difference is that this class extends the java.util.Observable class and calls its observers update method
 * when the selected button changes. 
 * </p>
 */
public class ButtonGroup extends Observable implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     *  The buttons list
     */
    private List<JToggleButton> buttons;
    /**
     * The current selection.
     */
    private JToggleButton selected;
    private ItemListener listener;

    /**
     * Constructor.
     */
    public ButtonGroup() {
        this.buttons = new ArrayList<JToggleButton>();
        this.selected = null;
        this.listener = new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                JToggleButton b = (JToggleButton) e.getItem();
                if (e.getStateChange()==ItemEvent.SELECTED) {
                    setSelected(b);
                } else {
                    if (selected==b) setSelected(null);
                }
            }
        };
    }

    /**
     * Adds a button to this group.
     * @param b the button to be added
     * @exception NullPointerException if the button is null
     */
    public void add(JToggleButton b) {
        if (b==null) throw new NullPointerException();
        buttons.add(b);
        b.addItemListener(listener);
        if (b.isSelected()) setSelected(b);
    }

    /**
     * Removes a button from this group.
     * @param b the button to be removed
     * @exception IllegalArgumentException if the button is unknown in this group
     * @exception NullPointerException if the button is null
     */
    public void remove(JToggleButton b) {
        if (b == null) throw new NullPointerException();
        if (this.buttons.remove(b)) {
            b.removeItemListener(this.listener);
            if (this.selected==b) setSelected(null);
        } else {
            throw new IllegalArgumentException();
        }
    }

    /**
     * Clears the selection such that none of the buttons in the
     * <code>ButtonGroup</code> are selected.
     */
    public void clearSelection() {
        if (selected != null) setSelected(null);
    }

    /**
     * Returns the selected button.
     * @return the selected button
     */
    public JToggleButton getSelected() {
        return this.selected;
    }

    /** Changes the selected button.
     * @param b the button to be selected (null deselects all buttons)
     * @exception IllegalArgumentException if the button is not in this group
     */
    public void setSelected(JToggleButton b) {
        if (b==this.selected) return;
        if ((b!=null) && (!this.buttons.contains(b))) throw new IllegalArgumentException();
        JToggleButton old = this.selected;
        this.selected = b;
        if (b!=null) b.setSelected(true);
        if (old!=null) old.setSelected(false);
        this.setChanged();
        this.notifyObservers(this.selected);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜