How to check the status of checkbox in java GUI?

前端 未结 3 1082
无人及你
无人及你 2021-01-05 12:32

I have around 200 hundred checkboxes in a Java GUI. Now I want to have the list of all checkboxes that have been checked by the user.

I can do it in one way like thi

3条回答
  •  情书的邮戳
    2021-01-05 13:23

    You really should have put these in an array or Collection so that you can just loop over them. eg.

    List allCheckBoxes = new ArrayList()
    allCheckboxes.add(new JCheckBox());
    

    etc.

    If you have all these checkboxes declared as members then there's no excuse to just put them in a list instead.

    In the meantime you could use a dodgy cast in a for loop (if all the checkboxes are on the same panel)

    boolean allSelected = true;
    for(Component component : myPanel.getComponents()) {
      if(component instanceof JCheckBox) {
        allSelected &= ((JCheckBox)component).isSelected();
      }
    }
    

    I'd recommend reading about Java arrays and collections before continuing

    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html

    http://java.sun.com/docs/books/tutorial/collections/index.html

提交回复
热议问题