【问题标题】:JavaFX - css doesn't work in my project, but can work in scene builderJavaFX - css 在我的项目中不起作用,但可以在场景构建器中工作
【发布时间】:2018-09-02 07:07:12
【问题描述】:

我正在学习使用 Scene Builder。我读过一些相同的问题,但我仍然很困惑。

我写了一个css来设置背景,这是我的css代码:

 @charset"UTF-8";
.bodybg{
    -fx-background-image: url('../background.jpg');
    -fx-background-size: 100% 100%; 
}

当我预览我的界面时,它工作了

但是当我在我的代码中使用fxml 时,背景消失了。

这是我的java代码:

public static void main(String[] args) {

        launch(args);
    }

    @Override
    public void start(Stage primaryStage){
        try {
            // Read file fxml and draw interface.
            Parent root = FXMLLoader.load(getClass().getResource("/demo/StartUI.fxml"));
            Scene scene = new Scene(root);


            primaryStage.setTitle("test");
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();


        } catch(Exception e) {
            e.printStackTrace();
        }
    }

【问题讨论】:

  • 项目资源中有CSS文件吗?另外,您可以发布您的 FXML 文件吗?
  • 你如何包含你的css?它是内联的,在 .fxml 文件中吗?还是在 标签内?您的项目结构如何?您是否从资源文件夹中读取了 fxml?
  • 如果您的 css 和 fxml 不在同一个目录中,那么相对路径“../”可能会搞砸,因为它找不到图像

标签: java css javafx fxml scenebuilder


【解决方案1】:

您可能没有在 fxml 文件中附加 css 表。现在使用任何文本编辑器(如 Windows 中的记事本)编辑您的 fxml 文件。

在您的 fxml 文件中的子标签之前编写此代码。

<stylesheets>
    <URL value="@your_css_file.css" />
</stylesheets>

这看起来像:

<AnchorPane id="AnchorPane" prefHeight="233.0" prefWidth="481.0" 
styleClass="mainFxmlClass" xmlns="http://javafx.com/javafx/8.0.102" 
xmlns:fx="http://javafx.com/fxml/1" fx:controller="ate.ChangePasswordController">

<stylesheets>
    <URL value="@your_css_file.css" />
</stylesheets>

   <children>

   </children>
</AnchorPane>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    相关资源
    最近更新 更多