Where does javafx.scene.image.Image(“flower.png”) look for flower.png?

后端 未结 3 1488
长发绾君心
长发绾君心 2020-11-27 07:36

I would like to know what the JavaFX Image constructor\'s relative path resolution algorithm is for:

  1. Stand-alone apps.
  2. Browser deployed apps.
相关标签:
3条回答
  • 2020-11-27 07:46
    1. search directory where class files( name of class getClass().getName().toString() ) related to your .java file are present, copy and paste your image there
    2. Image image=new Image(getClass().getResourceAsStream("yourImageName.jpg")); is must.

    In NetBeans the directory where classes are present NetBeansProjects/JavaFXProjectName/build/classes/packageName/

    0 讨论(0)
  • 2020-11-27 07:56

    The answer is "/" if case you are using getClass().getResourceAsStream(), i.e. the root of your jar file (inside it). Not user.dir nor where the package is hosted

    0 讨论(0)
  • 2020-11-27 08:03

    Then user provides relative path to new Image(String url) it will be relative against workdir of the app aka System.getProperty("user.dir")

    1. For stand-alone app it's a folder you started an application from
    2. For web-start app being run from command line (javaws myfxapp.jnlp) it works the same way as with standalone app
    3. For plugin start or webstart app loaded from browser you can't reliably be sure about workdir location. It depends on browser and even on installed plugins for that browser.

    So general direction is: for standalone apps use url same way as you'll use it in new File(String url). For jnlp/plugin use full url with protocol or Class.getResource() approach.

    Update: Please, note, this behavior is going to be clarified and changed in 2.2. See http://javafx-jira.kenai.com/browse/RT-18291

    The following comment is from RT-18291 and outlines the intended changes for 2.2:

    Martin Sladecek added a comment - May, 15 2012 10:53 AM After discussion with Richard Bair, we decided to change the current (undocumented) behavior for paths. Currently, they are treated as user.dir relative. All path, with or without leading slash will be now resolved as relative to classpath, which will be consistent with CSS and more corresponds to what might users expect. For user.dir relative paths, "file:" URL can be still used.

    0 讨论(0)
提交回复
热议问题