How to check that a JCheckBox is checked?
Asked Answered
B

2

73

How can I check if a JCheckBox is checked?

Brooch answered 30/8, 2010 at 11:29 Comment(0)
E
117

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Escobedo answered 30/8, 2010 at 11:33 Comment(0)
A
24

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}
Audacity answered 20/5, 2015 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.