Halfpint
Halfpint

Reputation: 4079

JavaFX - Check if a checkbox is ticked

I am trying to write some code to determine whether or not my checkbox is ticked, I am aware I can write something like to change its state to checked

checkbox.setSelected(true);

But I want to write something along the lines of

if(checkbox.setSelected(true)){
   write login-username to config file
} else {
   clear the config file
}

How would I go about doing this? I've been trauling through Oracle documentation but have yet to find anything useful

thanks.

Upvotes: 10

Views: 34685

Answers (2)

Neel Sanchala
Neel Sanchala

Reputation: 131

You can use .isSelected() to find out if the checkbox is ticked.

if (checkbox.isSelected()) {
   write login-username to config file
} else {
   clear the config file
}

Upvotes: 13

Alex
Alex

Reputation: 81

Have you tried registering a listener to the "selected" property of the checkbox? It would look something like this:

yourCheckbox.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            // TODO Auto-generated method stub
            if(newValue){

                // your checkbox has been ticked. 
                // write login-username to config file

            }else{

                // your checkbox has been unticked. do stuff...
                // clear the config file
            }
        }
    });

Upvotes: 5

Related Questions