简体   繁体   English

获取Java中所有选中的复选框

[英]Get all selected checkboxes in Java

I have a dialog in Java that presents ~ 15 checkboxes to the user. 我在Java中有一个对话框,向用户显示〜15个复选框。 Is there a way to get the names of all the checked checkboxes at once? 有没有办法一次获取所有选中复选框的名称? Currently, I'm looking one by one if they are selected, which isn't that fancy of a solution. 目前,如果要选择它们,我正在逐一寻找,这并不是解决方案的幻想。

I'm looking for something similar to Getting all selected checkboxes in an array but then in Java 我正在寻找类似于在数组中获取所有选中的复选框,然后在Java中查找的东西

When you are adding your Checkboxes to your dialog also keep a reference in a Collection of some sort. 当您将复选框添加到对话框时,还应在某种“集合”中保留引用。 Then when you want to see which are checked you can just Iterate over the collection and check the state of each of them. 然后,当您想查看已检查的对象时,可以遍历集合并检查每个对象的状态。 You can get the name by calling getText on it. 您可以通过在其上调用getText来获得名称。

List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
for( Component comp : panel.getComponents() ) {
   if( comp instanceof JCheckBox) checkboxes.add( (JCheckBox)comp );
}

This assumes all of the JCheckBox instances are a direct child of the container panel. 假定所有JCheckBox实例都是容器面板的直接子代。 If not then you'd need to recursively visit all the containers of panel using the same logic. 如果不是,那么您需要使用相同的逻辑递归访问面板的所有容器。 Now, while you can do this it's typically better to save these references as you created them into a list. 现在,尽管可以执行此操作,通常最好将这些引用创建时保存到列表中。 Then you can easily iterate over all of the checkboxes without having to do this code above. 然后,您可以轻松地遍历所有复选框,而不必执行上面的代码。 If you have embedded components it's better to ask the embedded component to perform whatever operation you want over the checkboxes it owns (as opposed to pulling them out of the component through a getter so you can mess them in some way). 如果您具有嵌入式组件,则最好让嵌入式组件通过其拥有的复选框执行所需的任何操作(而不是通过吸气剂将其从组件中拉出,以便以某种方式弄乱它们)。

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

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