Search code examples
checkboxjavafx

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.


Solution

  • 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
                }
            }
        });