I wanted to know how should I set icons on javaFX stage. I have found this method, but it did not work properly.
stage.getIcons().add(new Image(iconImagePath));
stage is an instance of javafx.stage.Stage, and I have imported javafx.scene.image.Image. This is the exception which we receive:
Invalid URL: Invalid URL or resource not found
Also, there is nothing wrong with the iconImagePath, its value is "G:/test.jpg" and there is a jpg file in the G drive named test. In addition, when we use ImageIO to read the same URL we can do it easily.
This example works. I placed an icon in the same folder/package as the source .java file.
Directory structure
The constructors of
javafx.scene.image.Image
expect a URI, not a (full) path. This URI can either be relative (e.g./images/flower.png
) or absolute (e.g.file:flower.png
).Strings like
G:/test.jpg
are no valid URLs and hence illegal.Try
file:g:/test.jpg
instead.Usually, the icons should be bundled with your application, so simply put the image file into your classpath (e.g. if you're using eclipse, put it into your 'src' directory) and use it like that:
don't forget that your icon must be in
32x32
or16x16
resolution, if not, it doesn't work.I use netbeans 8.2, if I use : stage.getIcons().addAll(new Image(getClass().getResourceAsStream("home-icon32.png")));
I have to put the image in src directory. Don't know why, but works only this way. I've tried putting it in build/classes, but negative.
The solution is: