JavaFX:在主类之外更改CSS文件

问题描述

一个与此相关的问题已得到解答,但我想知道如何在主类之外,控制器内部或某些更合适的类中更改CSS文件

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