JCheckBox Always Returning True/False But Not Changing

747 views Asked by At

Im currently facing an issue where I am able to add a checkbox to the screen and when clicked it swaps between states as required but when it comes to using the selection data to do things, it always returns the original value whether it be true or false;

My first slice of code was just using the isSelected(); method within an if statement that is constantly run each tick. SVelRand is my checkbox which I create using:

SVelRand = new JCheckBox("Random", true);
    SVelRand.setBounds(50, 30, 90, 20);

Then the checking code is as below:

boolean sel = SVelRand.isSelected();

    if(sel){

        System.out.print("Selected");

    }else{

        System.out.print("Not Selected");


    }

When I found this didn't work I tried to implement an item listener underneath where I create the jcheckbox but it still continues to return the initial value set.

SVelRand.addItemListener(new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            System.out.println(SVelRand.isSelected());
          }
        });

I am also drawing a Label and JTextField to the same panel before adding it to the frame incase that has any bearings. And the reason im using setBounds and not a layout is so I can add each component to precise locations to achieve a non standard layout.

Any help will be appreciated;

1

There are 1 answers

2
ivanivan On BEST ANSWER

In your action listener function just keep track of a (class scope) boolean

// way up above everything
public boolean toggleState=false;

// then later
SVelRand.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
  this.toggleState=(!this.toggleState);
  String message=(this.toggleState) ? "checked" : "unchecked";
  System.out.println("Checkbox is "+message);
}
});

If you are starting your checkbox as checked by default, simply change the initial value of toggleState to true