简体   繁体   English

如何在java GUI中查看复选框的状态?

[英]How to check the status of checkbox in java GUI?

I have around 200 hundred checkboxes in a Java GUI. 我在Java GUI中有大约200个复选框。 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 this: 我可以用这样的方式做到这一点:

jCheckBox1.isSelected();

But I don't want to write this line for 200 checkboxes. 但是我不想为200个复选框写这行。 Is there any way to do this through a for loop. 有没有办法通过for循环来做到这一点。

all the checkboxes have the name like jCheckBox1, jCheckBox2, jCheckBox3, jCheckBox4 ... jCheckBox200 所有复选框的名称都是jCheckBox1,jCheckBox2,jCheckBox3,jCheckBox4 ... jCheckBox200

You really should have put these in an array or Collection so that you can just loop over them. 你真的应该把它们放在一个数组或集合中,这样你就可以遍历它们。 eg. 例如。

List<JCheckBox> allCheckBoxes = new ArrayList<JCheckBox>()
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) 在此期间,您可以在for循环中使用狡猾的强制转换(如果所有复选框都在同一个面板上)

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 在继续之前,我建议您阅读有关Java数组和集合的内容

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

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

Ummm, what should I say? 嗯,我该怎么说?

OK, You should starts by using array to hold all check boxes you have so you can loop through it. 好的,你应该首先使用数组来保存你拥有的所有复选框,这样你就可以遍历它。

In case that is too late, you may have a another choice by loop though all elements on that container (only work if all checkboxes are on the same container). 如果为时已晚,您可以通过循环选择该容器上的所有元素(仅当所有复选框都在同一容器上时才有效)。 Something like ' jPanel1.getComponents() ' and then loop them only see which is a Checkbox. 像' jPanel1.getComponents() '之类的东西然后循环它们只看到哪个是Checkbox。

Anyway .. I think, you should put all those in an array and save yourself from a variable mess. 无论如何..我认为,你应该将所有这些放在一个数组中,以避免变得混乱。

Well, if you have your checkboxes in an array... you can do it in a loop. 好吧,如果你有一个数组中的复选框......你可以循环执行。

JCheckBox[] myBoxes = new JCheckBox[200];

//Some creation stuff here

for (int i=0; i<myBoxes.length; ++i) {
   if (myBoxes[i].isSelected()) {
       //Do stuff!
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM