首页 文章

在JavaFX项目中加载fxml文件时出错

提问于
浏览
2

我一直在研究桌面应用程序,我需要使用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.

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

2 回答

  • 4

    在JavaFX中,如果要加载fxml文件,请使用FXMLLoader,

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

    要加载样式表用作 .

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

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

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

  • 3

    尝试使用此启动方法并将目录 application/<NAME>.fxml 放在 Main.class 是fxml文件的同一目录中,使用 getStylesheets.add(...) 加载静态 FXMLLoader.load() 方法,可以将.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();
        }
    

相关问题