Java check if Checkbox is checked

天大地大妈咪最大 提交于 2019-12-05 08:07:01

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");
}

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

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

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

you can try this code

// check is ckeck box id
if (check.isSelected()) {
           // your code for checked;
 } else {
           // our code for not checked;
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!