javafx find the right path

馋奶兔 提交于 2021-02-11 17:26:35

问题


I get following structure:

project
|---+build
|---+dist
|---+nbproject
|----src
|-------client
|----------stuff
|-------------controller
|----------------DefaultController.java
|-------------files
|-------------fxml
|----------------DefaultFXML.fxml
|-------------img
|-------------lib
|---------------ContentManager.java
|-------------root
|---------------StartClass.Java
|---+build.xml
|---manifest.mf

I'm setting in the ContentManager the fxml-Files like:

public static final String 
        DEFAULT_SCREEN_FXML = "../fxml/Default.fxml";

But i get allways a nullPointerException. And i dont want to work with absolute Path. So how to finde out the relative path? And is it right to set the controller of the fxml-file with:

fx:id="client.stuff.controller.DefaultController"

??


回答1:


When you deploy your application, you typically create a jar file which includes the class files and all the resources. You need to load the fxml file from inside the jar file, i.e. as a resource. In this context, the path element ".." doesn't really mean anything.

Use

public static final String 
        DEFAULT_SCREEN_FXML = "/client/stuff/fxml/Default.fxml";

(the path is relative to the classpath).

and of course load it with

FXMLLoader loader = new FXMLLoader(getClass().getResource(DEFAULT_SCREEN_FXML));

or something similar.




回答2:


is it right to set the controller of the fxml-file with...fx:id...?

No, this is totally wrong. You should set the controller using fx:controller, not fx:id.

fx:id is for mapping @FXML elements in controllers to elements defined in an FXML document, it is not for mapping the controller class itself.

Refer to the Introduction to FXML document for more information.

So, don't use:

fx:id="client.stuff.controller.DefaultController"

Instead use:

fx:controller="client.stuff.controller.DefaultController"

James's answer for the other part of your question to do with path resolution is correct.



来源:https://stackoverflow.com/questions/23188511/javafx-find-the-right-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!