【问题标题】:Error loading fxml file in a JavaFX project在 JavaFX 项目中加载 fxml 文件时出错
【发布时间】:2014-04-27 06:09:30
【问题描述】:

我一直在开发需要使用 JavaFX 的桌面应用程序。我在 Eclipse 的 JavaFX 项目中创建了一个fxml 文件。我在场景构建器中构建场景。当我尝试运行主 Java 文件时,使用场景构建器对 fxml 文件所做的更改没有反映在主窗口上。屏幕显示为空白。这是我的代码。

public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    try {
        AnchorPane  root = new AnchorPane();

        Scene scene = new Scene(root,400,400,Color.BLACK);
        scene.getStylesheets().add(getClass().getResource("/application/sample.fxml").getPath());
        primaryStage.setTitle("FXML Welcome");

        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}

这是我的sample.fxml文件代码:

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<?scenebuilder-background-color 0x00ffa3ff?>

<AnchorPane prefHeight="379.0" prefWidth="549.0001220703125" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2">

<children>
<Button layoutX="219.0" layoutY="156.0" mnemonicParsing="false" text="hello" />
</children>
</AnchorPane>

我得到的错误是:

     WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "/F:/eclipse_progs/examplefx/bin/application/sample.fxml" not found.

但指定错误中的位置包含它所引用的文件。任何人都可以解释错误的原因。是代码问题还是插件问题?

【问题讨论】:

  • 这是因为,您以错误的方式加载 fxml 文件。您应该使用 FXMLLoader 加载 fxml 文件。 scene.getStyleSheets() 仅用于加载 css 文件。

标签: java eclipse javafx fxml scenebuilder


【解决方案1】:

试试这个启动方法,把你的目录application/&lt;NAME&gt;.fxml放在你Main.class所在的同一个目录下 使用静态 FXMLLoader.load() 方法加载 fxml 文件 使用getStylesheets.add(...),您可以将 .css 文件添加到您的场景中。

    @Override
    public void start(Stage primaryStage) throws IOException {

        Parent parent = FXMLLoader.load(getClass().getResource("application/demo.fxml"));
        Scene scene = new Scene(parent);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

【讨论】:

    【解决方案2】:

    在JavaFX中,如果你想加载一个fxml文件,那么使用FXMLLoader作为,

    FXMLLoader.load(getClass().getResource("application/sample.fxml"));
    

    加载样式表使用 as。

    scene.getStlyeShees().add(getClass().getResource("application/sample.css").toExternalForm);
    

    在您的代码中,您将 fxml 文件添加到场景的样式表列表中,这是错误的。尝试使用上述 FXMLLoader 加载您的 fxml 文件。

    参考文档:http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-07
      • 2021-10-31
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      相关资源
      最近更新 更多