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

huangapple go评论75阅读模式
英文:

JavaFX: Changing CSS file outside of Main class

问题

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

package calc;

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

public class Controller {
    @FXML
    private void skinSelector(ActionEvent event) {
        // 这里是魔法发生的地方!
    }
}
英文:

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

以下是您要翻译的内容:

这可能会对您有所帮助。

项目结构

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;
}
英文:

This will probably help you.

project structure

main.fxml

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

Controller.java

public class Controller {
@FXML
private Pane rootPane;

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

theme1.css

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

theme2.css

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

huangapple
  • 本文由 发表于 2020年8月13日 11:05:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63387559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定