Bestial Wraith
Bestial Wraith

Reputation: 51

How to Check(Marked as checked) buttons in a program(or a checkbox) from just one Button?

Here is my question.Lets say that somebody made a checkbox in java and he is using it in a GUI interface so that the user can select a variety of options.Then the programmer wants to create a button inside the checkbox so that when the user checks that button all the other options will be checked as well.And when he unchecks that button of course all the other buttons will be unchecked.How is that possible in java?

Example :

o1 = new JCheckBox("Option 1");
o2 = new JCheckBox("Option 2");
o3 = new JCheckBox("Option 3");
All = new JCheckBox("All");

.....

CheckBoxHandler listener = new CheckBoxHandler();
All.addItemListener(listener);

......

Lets assume that the following code is on a class that was created as it implements ItemListener

public class CheckBoxHandler implements ItemListener
{
 public void itemStateChanged(ItemEvent e)
  {
    if (e.getSource()==All)
      if (e.getStateChange()==ItemEvent.SELECTED)
        {
          .... <------ (!!!)Here inside I am currently stack and I do not know how to 
          add the correct code in order to have all the other buttons checked.
        }
   }
 }

Any help provided is really appreciated :)

Upvotes: 4

Views: 203

Answers (3)

Daniel
Daniel

Reputation: 2515

CheckBoxes can have ActionListeners. Why not add an ActionListener to all the checkboxes that then checks if the one selected is checked or not and calls setSelected(true) or setSelected(false) on each one?

If you have a known small number of checkboxes (such as the 3 you talked about), you may just want to hard code it. However, if you need to make it modular or have a large number of check boxes, you can always store them in a data structure (as Juvanis said, an array would probably work nicely) and loop it

Upvotes: 2

Andreas Fester
Andreas Fester

Reputation: 36640

You can call setSelected() on the JCheckbox (inherited from AbstractButton):

...
o1.setSelected(true); // or false
...

As @Juvanis mentions, instead of having three different references for o1, o2 and o3, you should use an array. Then, you can do something like

for( JCheckbox cb : checkboxes ) {
    cb.setSelected(true);
}

to set all checkboxes in the array as checked.

Upvotes: 2

Juvanis
Juvanis

Reputation: 25950

Make use of the concept of array.

JCheckBox[] checkboxes = new JCheckBox[10];

When you need to apply some operation to all checkboxes, iterate over the array:

for( JCheckbox cb : checkboxes )
   cb.doStuff();

Upvotes: 2

Related Questions