Java check if Checkbox is checked

安稳与你 提交于 2019-12-22 05:37:08

问题


I use:

    CheckboxGroup cg = new CheckboxGroup();
    Checkbox c1 = new Checkbox("A", false, cg);
    Checkbox c2 = new Checkbox("B", false, cg);
    Checkbox c3 = new Checkbox("C", true, cg);

To create a group of three checkboxes. Now, I want to check which one of them is checked. I use:

if (c1.isSelected()) { }

but this gives The method isSelected() is undefined for the type Checkbox... Recommended solution is add cast to c1, I do so and it gives Cannot cast from Checkbox to AbstractButton... Again, how can I just check if a Checkbox if checked?


回答1:


Use getState()

boolean checked = c1.getState();
if(c1.getState()) {
  //c1 is checked
} else if (c2.getState()) {
  //
}

OR

Checkbox cb = cg.getSelectedCheckbox();
if(null != cb) {
  //not checked
} else {
  System.out.println(cb.getLabel() + " is checked");
}



回答2:


You can use Checkbox::getState() or (as said in the comment) CheckboxGroup#getSelectedCheckbox()




回答3:


1st of all java.awt.Checkbox doesn't have .isSelected() method in its super class, which is java.awt.Component.

https://docs.oracle.com/javase/7/docs/api/java/awt/Checkbox.html

please check the above link for Methods inherited from class java.awt.Component

2nd .isSelected() method can be used if you use JCheckBox from javax.swing.JComponent; but not CheckBox of AWT...

please go through below link.. and you can find .isSelected() which is inherited from javax.swing.AbstractButton;

https://docs.oracle.com/javase/7/docs/api/javax/swing/JCheckBox.html




回答4:


judging by your use of isSelected i concluded you have 1 of 2 mistakes:

  1. you want to use check box, if that is the case, then you should use c1.getState() and not isSelected()
  2. you need RadioBox instead of CheckBox and then you can use the isSelected() method. check here about the two



回答5:


you can try this code

// check is ckeck box id
if (check.isSelected()) {
           // your code for checked;
 } else {
           // our code for not checked;
 }


来源:https://stackoverflow.com/questions/27423485/java-check-if-checkbox-is-checked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!