舞台图标javafx中出现NullPointerException错误

时间:2017-12-29 13:00:38

标签: java javafx nullpointerexception

文件" icon.png"与类在同一文件夹中。但是,如果我只是使用(新的图像(" icon.png")),那么它说java.lang.IllegalArgumentException:无效的URL:无效的URL或资源未找到。但是现在添加了getClass()。getResource ...我得到了这个错误。这是我的代码:

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;

public class Main extends Application {
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("NewFile.fxml"));
            Scene scene = new Scene(root);
            primaryStage.setResizable(false);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.getIcons().add(new Image(getClass().getResource("icon.png").toExternalForm()));
            primaryStage.show();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

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

这是错误:

java.lang.NullPointerException
    at application.Main.start(Main.java:19)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(Unknown Source)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(Unknown Source)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(Unknown Source)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
    at java.base/java.lang.Thread.run(Unknown Source)

请帮我修理一下。提前谢谢!

1 个答案:

答案 0 :(得分:0)

由于location of your image is not in the proper position引用了不存在的内容而导致NullPointerException错误 您可以编辑您的帖子,向我们展示您的项目建设 工作应该是这样的事情!

enter image description here