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?
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");
}
您可以使用Checkbox::getState()
或(如评论中所述) 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
I found the isChecked() method to be the winner.
// Check to see if box is checked
if (c1.isChecked()) {
// Your code if the box is checked
} else {
// Your code if the box is not checked
}
judging by your use of isSelected
i concluded you have 1 of 2 mistakes:
c1.getState()
and not isSelected()
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.