Tradução: há uma versão em Português desse artigo.
For some classes like javafx.scene.image.Image is easy load an image from a external resource like:
ImageView {
image: Image {
url: "http://example.com/myPicture.png"
}
}
or a resource inside your own Jar file with the __DIR__ constant:
ImageView {
image: Image {
url: "{__DIR__}/myPicture.png"
}
}
But for other classes loading a internal resource (inside your own jarfile) is not so direct. For example, in the article Parsing a XML Sandwich with JavaFX I had to place the XML file in a temp directory. A more elegant way would be:
package handlexml;
import java.io.FileInputStream;
import javafx.data.pull.*;
import javafx.ext.swing.*;
import javafx.scene.Scene;
import javafx.stage.Stage;
class Resource{
function getUrl(name:String){
return this.getClass().getResource(name);
}
function getStream(name:String){
return this.getClass().getResourceAsStream(name);
}
}
var list = SwingList { width: 600, height: 300}
var myparser = PullParser {
documentType: PullParser.XML;
onEvent: function (e: Event) {
var item = SwingListItem {text: "event {e}"};
insert item into list.items;
}
input: Resource{}.getStream("my.xml");
}
myparser.parse();
Stage {
title: "Map"
scene: Scene {
content: list
}
}
With a simple XML file called my.xml inside your package.
And we get the same result as before, but all files inside our Jars.
References:
- Hildeberto’s article Acessing Resources Inside of JAR Files
[…] there’s a English version of this […]
look, I want to load an image from a directory in my hd, but the app could’t find the file.
Can you help me?
Thanks.