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);  }}
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of