Skip to content
Advertisement

Javafx- how this multiple toggle buttons (in one group) actions are correctly configure for my need

This is what happens. But i need to return colors when i press other toggle buttons

What I need to do is colors need to be back to blue after clicking on another button (while toggling another button need to untoggle toggled buttons)

Problem is when I toggle 1st button (working correctly – changing color on box). But when I press 2nd button while selected 1st button, 1st button color box color not returning to blue.

JavaScript

Advertisement

Answer

You don’t need to set onAction property for the ToggleButtons. Just add a ChangeListener to the selectedToggle property of the ToggleGroup. In that ChangeListener you need to do two things:

  1. Change the color of the Rectangle associated with the newly selected ToggleButton.
  2. Revert the color of the previously selected ToggleButton.

I reverse engineered a FXML file based on the code in your question. The below code is a SSCCE with minimal changes to your code just to show how to use a ChangeListener.

File: fxmldocu.fxml

JavaScript

Your FXMLDocumentController with added ChangeListener

JavaScript

Note that the “controller” class does not need to implement Initializable interface. It can simply declare a initialize method instead, as I have done in the above code.

Finally, an Application class for running the application.

JavaScript

Also note that another possible alternative – which I did not explore – could be to bind the selectedToggle property of ToggleGroup with the selected property for each ToggleButton.

Lastly, (and before kleopatra adds a comment regarding it 🙂 consider using Java naming conventions.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement