【发布时间】:2013-12-28 17:52:02
【问题描述】:
我正在尝试让我的 JavaFX 程序运行,但遇到了一些困难。我不断收到“java.lang.NullPointerException:需要位置”的错误。 fxml 文件与 Application 类在同一个包中。这是我非常简单的代码:
package com.kromalights.designer.entry;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
primaryStage.setTitle("Kromalights Designer");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这是我的 main.fxml 文件的副本:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<?scenebuilder-stylesheet mailStyles.css?>
<?import java.net.*?>
<BorderPane prefHeight="300.0" prefWidth="300.0" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/2.2"
fx:controller="com.kromalights.designer.entry.Controller">
<bottom>
<Pane prefHeight="200.0" prefWidth="200.0"/>
</bottom>
<center>
<Pane prefHeight="200.0" prefWidth="200.0"/>
</center>
<left>
<VBox prefHeight="200.0" prefWidth="100.0"/>
</left>
<top>
<HBox prefHeight="100.0" prefWidth="200.0"/>
</top>
<stylesheets>
<URL value="@mainStyles.css" />
</stylesheets>
</BorderPane>
控制器类确实存在并且在 fxml 文件中指定的包中。我所有的名字都是正确的,并且是我认为应该在的地方。我错过了什么?我确实尝试重命名我的 fxml 文件,以防出现名称问题。请帮忙。仅供参考,我在 OSX 上使用 Intellij IDEA。
更新:这是一个 Maven 问题。我为这个项目设置了 Maven,这导致了这个问题。我暂时删除了 Maven,这样我就可以在没有它的情况下继续工作。有没有人知道我在使用 Maven 时如何最好地处理这个问题?
【问题讨论】:
-
mainStyles.css 在哪里?它是否也与您的 FXML 和主应用程序类位于同一路径位置?
-
是的。这不是我的问题。如果我从我的 xml 文件中删除样式表信息,它仍然无法运行。这是我认为可能是问题的第一件事,所以我在没有样式表的情况下对其进行了测试。
-
因此,在 Maven 环境中,您的 fxml 必须转到 main/resources,否则它将获取运行时类路径的一部分。检查你从 getResource("main.fxml) 得到什么,我认为你从中得到 null!