简体   繁体   English

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

[英]JavaFX: Changing CSS file outside of Main class

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.有一个与此相关的问题已经得到解答,但我想知道如何在主 class 和 controller 或更多合适的类之外更改 CSS 文件。

package calc;

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

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

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 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主题1.css

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

theme2.css主题2.css

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM