How to check (marked as marked) buttons in the program (or checkbox) with just one button?

Here is my question. It is said that someone made a checkmark in java, and he uses it in the GUI interface so that the user can select many options. Then the programmer wants to create a button inside the flag so that when the user checks this button, all other parameters will also be checked. And when he canceled this button, of course, all other buttons will be removed. How is this 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); 

......

Suppose the following code is in a class that was created because 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 :)

+4
source share
3 answers

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

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

As @Juvanis mentions, instead of three different links 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 the checkboxes in the array as noted.

+2
source

Use the concept of an array .

 JCheckBox[] checkboxes = new JCheckBox[10]; 

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

 for( JCheckbox cb : checkboxes ) cb.doStuff(); 
+2
source

CheckBoxes can have ActionListeners. Why not add an ActionListener to all the checkboxes, which then check whether the selected one is selected or not, and whether it setSelected(true) or setSelected(false) ?

If you have a known small number of flags (for example, 3 of which you spoke about), you may just want to write it hard. However, if you need to make it modular or have a large number of flags, you can always store them in the data structure (as Juvanis said, the array will probably work well) and loop it

+2
source

Source: https://habr.com/ru/post/1487898/


All Articles