joki00
joki00

Reputation: 83

JavaFX ToggleButton set color and restore default color

What is normal background color and border color on toggle button? example:

i.toggle11.setOnAction(e->{
        if(i.toggle11.isSelected()){
            i.toggle11.setStyle("-fx-background-color:red");
             i.toggle12.setStyle("-fx-background-color:white");
             i.toggle13.setStyle("-fx-background-color:white");
        }
        else {
             i.toggle11.setStyle("-fx-background-color:white");
        }
    });

I want to after this action to put other toggles 'normal color'(same when togglebutton was created)

Upvotes: 2

Views: 9359

Answers (1)

DVarga
DVarga

Reputation: 21799

To answer how to add/remove styles

The simplest approach if you color your ToggleButtons by adding a CSS styleclass, then when it is not needed anymore you remove them, therefore it will have the same style as before your formatting.

Example

Code to add

i.toggle11.setOnAction(e->{
        if(i.toggle11.isSelected()){
            i.toggle11.getStyleClass().add("red-button");
            i.toggle12.getStyleClass().add("white-button");
            i.toggle13.getStyleClass().add("white-button");
        }
        else{
             i.toggle13.getStyleClass().add("white-button");
        }
    });

Then Code to remove

i.toggle11.getStyleClass().removeAll("red-button", "white-button");

CSS

.red-button {
    -fx-background-color: red;
}

.white-button {
    -fx-background-color: white;
}

Just make sure that you have added the stylesheet which contains the CSS styles like:

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

But

I don't know what you want to achieve, but if you want to just simply color your ToggleButton when it is selected, you can also overwrite .toggle-button:selected in your stylesheet and no other styling needed:

.toggle-button:selected {
    -fx-background-color: red;
}

It is always the simplest way to overwrite existing CSS classes and pseudoclasses. This is a good starting point to learn working with ToggleButtons and to style them: Using JavaFX UI Controls.

You can for example check the available style classes for .toggle-button here and also you can check the CSS reference guide.

Upvotes: 1

Related Questions