gpt4 book ai didi

java - 如何从 JavaFX 中的 Java Controller 控制 CSS 文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:51 24 4
gpt4 key购买 nike

我已经构建了一个具有一个主题的应用程序,当我完成它时我使用了一个 CSS 文件我试图让用户选择他喜欢的选择颜色并且 CSS 文件包含在每个的 FXML 文件中阶段

 *{
-fx-primary :#2A2E37 ;
-fx-secondary : #FFFF8D;
-fx-primarytext : #B2B2B2;
-fx-blue: #1976D2;
-fx-red: #FF0000;
-fx-green:#2E7D32;

}
.root{
-fx-background-color: -fx-primary;
}

我想要一些方法来改变我的 -fx-primary 的值,例如颜色将从调色板中选择(我可以做到)对于 fxml,我使用简单的方法

<AnchorPane fx:id="rootAnchoreFW" prefHeight="800.0" prefWidth="767.0" stylesheets="@../Style/myTheme.css" >

最佳答案

您可以为这种颜色制作多个主题。比如一个文件叫themeRed.css, themeBlue.css

   .root{
-fx-font-size: 14pt;
-fx-font-family: "Tahoma";
-fx-base: #DFB951;
-fx-background: #A78732;
-fx-focus-color: #B6A678;
}

并且,您有一个可以更改颜色或主题的按钮。

你可以在你的应用中设置你的主题,像这样:

public String themeRed = getClass().getResource("themeRed.css").toExternalForm();public String themeBlue = getClass().getResource("themeBlue.css").toExternalForm();

在按钮点击 Action 中,或者在点击发生时触发的方法中,你可以使用:

btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
scene.getStylesheets().remove(themeRed);
scene.getStylesheets().add(themeBlue);
System.out.println("Stylesheets: " + scene.getStylesheets());
//You can see the stylesheet being used
}
});

您可以使用它来改变主题。

另一种选择是,如果您只是更改,比方说,一个 css 行,例如一个按钮中的背景,您可以在您想要的每个元素中使用 setStyle 方法。

例如:

btn.setStyle("-fx-background: #A78732;");

关于java - 如何从 JavaFX 中的 Java Controller 控制 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com