Select All Checkboxes

Question:
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?

Answer:
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)it.next();            // 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);  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a