问题
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:
- you want to use check box, if that is the case, then you should use
c1.getState()
and notisSelected()
- you need
RadioBox
instead ofCheckBox
and then you can use theisSelected()
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