0

There is a question related to this that was already answered but I would like to know how to change the CSS file outside of the main class and inside the controller or perhaps some more appropriate classes.

package calc;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;

public class Controller {
    @FXML
    private void skinSelector(ActionEvent event) {
        // Where the magic happens!
    }
}
1
  • 1
    Just the same as always: grab the scene and are whatever stylesheet you want Commented Aug 13, 2020 at 3:40

1 Answer 1

1

This will probably help you.

project structure

main.fxml

<Pane fx:id="rootPane" stylesheets="@theme1.css" styleClass="pane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <children>
        <Button layoutX="200.0" layoutY="200.0" onAction="#press" text="Button" />
     </children>
</Pane>

Controller.java

public class Controller {
@FXML
private Pane rootPane;

@FXML
private void press(ActionEvent actionEvent) {
        rootPane.getStylesheets().clear();
        rootPane.getStylesheets().add(
                                getClass()
                                .getResource("theme2.css")
                                .toExternalForm()
                            );
    }
}

theme1.css

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

theme2.css

.pane{
    -fx-background-color: black;
}
Sign up to request clarification or add additional context in comments.

3 Comments

If you want to change the style sheets on the scene, instead of just in the root, then you can replace rootPane.getStylesheets() with rootPane.getScene().getStylesheets()
@James_D Most often this doesn't make sense, my Pane is the root panel.
It depends on the use case, of course, but if you wanted the change to persist after loading a new FXML file into the same scene, for example, you'd want to set the stylesheet on the scene.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.