-1

When I check if my Checkbox is selected or unselected, the function isSelected() doesn't work.

I have this error: the method isSelected() is undefined for the type Checkbox, and I don't know why.

Can you explain me where the problem is or tell me if there is an other solution to check if my Checkbox is selected ?

Code:

import javax.swing.*;
import java.awt.event.*;

public class Example extends JFrame{
    public JCheckBox one;

    public Example() {
        one = new JCheckBox("CT scan performed");
        one.addItemListener(new CheckBoxListener());
        setSize(300,300);
        getContentPane().add(one);
        setVisible(true);
    }

    private class CheckBoxListener implements ItemListener{
        public void itemStateChanged(ItemEvent e) {
            if(e.getSource()==one){
                if(one.isSelected()) {
                    System.out.println("one has been selected");
                } else {System.out.println("nothing");}
            }
        }
    }

    public static void main(String[] args) {
        new Example();
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • When I paste it in Eclipse as-is and run it, it works and I can click the checkbox and the System.out gives the correct outputs. Not sure what the problem is. – Friso van Dijk Apr 04 '14 at 01:20

1 Answers1

3

Your code compiles for me, so there may be an error somewhere else. Myself, though, I'd use the ItemEvent state. For example:

private class CheckBoxListener implements ItemListener {
  public void itemStateChanged(ItemEvent e) {
     if (e.getStateChange() == ItemEvent.SELECTED) {
        System.out.println("one has been selected");
     } else {
        System.out.println("nothing");
     }
  }
}

Edit
Is your error truly, "the method isSelected() is undefined for the type Checkbox"? If so, are you declaring one as a CheckBox variable or as a JCheckBox variable? Or do you have another class called Checkbox (note the lower-case b)?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373