Java check if Checkbox is checked
Asked Answered
P

6

8

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?

Pulchritude answered 11/12, 2014 at 12:58 Comment(2)
What's wrong with CheckboxGroup#getSelectedCheckbox()?Destalinization
Radio buttons seems more appropriate than checkboxes if they are mutually exclusive.Roobbie
D
8

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");
}
Darrondarrow answered 11/12, 2014 at 13:0 Comment(0)
H
1

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

Hardhearted answered 11/12, 2014 at 13:0 Comment(0)
A
1

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

Algorithm answered 15/2, 2017 at 7:35 Comment(0)
A
1

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
 }
Anaxagoras answered 29/12, 2019 at 4:56 Comment(0)
H
0

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
Halona answered 11/12, 2014 at 13:11 Comment(0)
C
-1

you can try this code

// check is ckeck box id
if (check.isSelected()) {
           // your code for checked;
 } else {
           // our code for not checked;
 }
Collectivize answered 1/6, 2016 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.