JavaFX:在 Main class 之外更改 CSS 文件

JavaFX: Changing CSS file outside of Main class

有一个与此相关的问题已经得到解答,但我想知道如何更改主 class 外部和控制器内部的 CSS 文件,或者可能更合适classes.

package calc;

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

public class Controller {
    @FXML
    private void skinSelector(ActionEvent event) {
        // Where the magic happens!
    }
}

这可能会对您有所帮助。

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