Select All Checkboxes

Select All Checkboxes

I have several checkboxes and I want one checkbox tocause all of the checkboxes to be selected when it is selected. Howcan I do this?

Even though the combined AWT and Swing packages provide an enormousbreadth of functionality, they do not cover every scenario you willrun into. The ButtonGroup class is designed to implement radiobuttons, a group of buttons whose selected states are mutuallyexclusive. Therefore it is not suitable for your task. Implementingthe functionality on your own, however, is rather easy.

A “select all” button should cause all the buttons it is associated withto be selected when it is selected. It should also become deselectedwhen any of the other buttons are deselected while it is selected.I have provided a code example implementing a SelectAllGroup classthat will do this for you. The class itself implements theActionListener interface. That is so it can register itself as anActionListener with all of the buttons in order to detect selectionand deselection events. It uses a Vector to store all of the buttonsin the group except for the select all button. When a button is addedto the group, it is stored in the Vector and the SelectAllGroup objectadds itself as an ActionListener of the button. When a button isremoved from the group, it is removed from the Vector and theSelectAllGroup object removes itself as an ActionListener of thebutton. The select all button is referenced by a separate_selectAllButton member variable that is set withsetSelectAllButton(). The SelectAllGroup object also adds itself asan ActionListener of this button.

All the grunt work is done in actionPerformed(), which implements asimple state machine with explicit Java code. If the ActionEventoriginates from the “select all” button and the button is selected, then themethod iterates through all of the buttons, invoking doClick() if theyare not already selected. I use doClick() instead of setSelected()because setSelected() will not cause any of the buttons’ActionListeners to be notified. If the ActionEvent comes from one ofthe buttons in the group, then the “select all” button is deselectedonly if it is currently selected and the button in the group is beingdeselected.

import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;import javax.swing.event.*;public class SelectAll extends JFrame {  public static class SelectAllGroup implements ActionListener {    AbstractButton _selectAllButton;    Vector _buttons;        public SelectAllGroup() {      _selectAllButton = null;      _buttons = new Vector();    }    public void setSelectAllButton(AbstractButton b) {      if(_selectAllButton != null)        _selectAllButton.removeActionListener(this);      _selectAllButton = b;      _selectAllButton.addActionListener(this);    }    public boolean addButton(AbstractButton b) {      if(_buttons.add(b)) {        b.addActionListener(this);        return true;      }      return false;    }    public boolean removeButton(AbstractButton b) {      if(_buttons.remove(b)) {        b.removeActionListener(this);        return true;      }      return false;    }    public void actionPerformed(ActionEvent e) {      Object source = e.getSource();      AbstractButton button;      if(_selectAllButton != null &&         _selectAllButton.equals(source) &&         _selectAllButton.isSelected())        {          Iterator it = _buttons.iterator();          while(it.hasNext()) {            button = (AbstractButton);            // Using setSelected will not trigger an actionEvent,            // so we use doClick() instead.            if(!button.isSelected()) {              // We want all the other ActionListeners              // to be called, but not ourselves.              button.removeActionListener(this);              button.doClick();              button.addActionListener(this);            }          }        } else if(_buttons.contains(source)) {          button = (AbstractButton)source;          if(!button.isSelected() && _selectAllButton.isSelected()) {            _selectAllButton.removeActionListener(this);            _selectAllButton.doClick();            _selectAllButton.addActionListener(this);          }        }    }  }  SelectAllGroup _buttonGroup;  public SelectAll() {    Container contentPane = getContentPane();    JCheckBox checkBox;    contentPane.setLayout(new FlowLayout());    _buttonGroup = new SelectAllGroup();    checkBox = new JCheckBox("Select All");    _buttonGroup.setSelectAllButton(checkBox);    contentPane.add(checkBox);    for(int i = 1; i <= 5; i++) {      checkBox = new JCheckBox(Integer.toString(i));      _buttonGroup.addButton(checkBox);      contentPane.add(checkBox);    }  }  public static final void main(String[] args) {    SelectAll frame;    frame = new SelectAll();    frame.addWindowListener(new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }      });    frame.pack();    frame.setTitle("Select All Button Demo");    frame.setVisible(true);  }}
See also  10 Best Apps to Help You Read More Books in Less Time

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist