2

I have JavaFX application in which I want to call from static Java method this code.

Image icon = new Image(getClass().getResource("/images/system-help.png").toExternalForm());

But I get this warning message:

non-static method getClass() cannot be referenced from a static context

Can you tell me what is the proper way to rewrite this code in order to use it into static method?

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
user1285928
  • 1,328
  • 29
  • 98
  • 147
  • 1
    possible duplicate of [calling non-static method in static method in Java](http://stackoverflow.com/questions/2042813/calling-non-static-method-in-static-method-in-java) – jlordo Jul 03 '13 at 17:32

3 Answers3

11

A word of advice => don't do this.

In general Jeffery's answer provides a recipe for initializing static resources, however it may not be a good idea to apply it to loading a JavaFX Image.

Due to RT-30796 Cannot create a JavaFX Image until "Internal graphics" are initialized, it is not advised to attempt to create a JavaFX Image in a static context.

The issue in RT-30796 which prevents loading of a JavaFX Image in a static context before the JavaFX internal graphics engine is initialized may or may not be addressed in a future version of JavaFX. (A sign up is required to view the issue tracker, but anybody can sign up to view it).

Instead, I recommend modifying your application logic to create your image in a non-static context, once you are sure that the JavaFX toolkit has been appropriately initialized for your application (for example once your application's init or start methods have been invoked or your JFXPanel created).

Additionally, for loading a JavaFX image, I do not recommend using ImageIO. ImageIO creates AWT images which you then need to convert to JavaFX images. Using the JavaFX Image constructor is a more direct route and will work on compact Java profiles on embedded platforms where AWT and ImageIO may not be available.

jewelsea
  • 150,031
  • 14
  • 366
  • 406
7

The way to access the class in a static context is to use the class literal from the enclosing class.

Ex:

public class Foo {
    private static final Image icon;
    static {
        icon = new Image(Foo.class.getResource(...));
    }
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • Is there any more simple solution? – user1285928 Jul 03 '13 at 17:37
  • 3
    @user1285928 Isn't this solution simple enough? You could also use [`ImageIO`](http://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html) to load the images for you, as stated in the other answer. – Jeffrey Jul 03 '13 at 17:41
4

Use

MyClass.class.getResource

or try:

ImageIO.read(new File("/images/system-help.png"))
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136