Problem with getResource () when getting an image

1

I have a package called app and within this I have two packages one called res and another graphics, within this last one I have a class with a method, which is responsible for creating an ImageView

private ImageView getImageViewFrom(String path){
    return new ImageView(getClass().getResource(path).toString());
}

When I call it, I call it an argument "../res/image.png" to get the image, however, it throws a NullPointerException in the line of that method, and it did not understand, because, that is, the file exists in app / res / image.png and the class in app / graphics / GraphicLoader.java.

GraphicLoader Class

package app.graficos;

import app.modelo.Juego;
import javafx.scene.layout.GridPane;
import java.lang.UnsupportedOperationException;

public final class GraphicLoader{

private GraphicLoader(){
    throw new UnsupportedOperationException();
}

public static GridPane createAndAddWithGraphics(Juego juego, GridPane gp){
    for(int i=0; i<juego.getTablero().getFilas(); i++){
        for(int j=0; j<juego.getTablero().getColumnas(); j++){
            gp.add(getImageViewFrom("../res/0.PNG"));
        }
    }

    return gp;

}

private static ImageView getImageViewFrom(String path){
    return new ImageView(getClass().getResource(path).toString());
}
}
    
asked by bruno Diaz martin 13.09.2018 в 18:35
source

2 answers

0

The route for this case is \app\res\image.png but a better way to do this is using code to get the route since it must have the one where it is installed and it is like this:

ServletContext servletContext = (ServletContext)
FacesContext.getCurrentInstance().getExternalContext().getContext();
String realPath = servletContext.getRealPath("/");

String path = realPath + "app" + File.separator + "res" + File.separator;
    
answered by 13.09.2018 в 19:30
0

The problem is not the reference of your file because the path defined according to your file structure is correct.

"../res/<NOMBRE ARCHIVO DE IMAGEN>"

What happens is that if you do not have a correct route, in this case you must validate your method:

 private ImageView getImageViewFrom(String path){
    URL imagePath = getClass().getResource(path);

    if(imagePath != null) {
        return new ImageView(imagePath.toString());
    }else{
        return null;
    }
}

Now if the path defined for image does not exist you can add or not the ImageView:

  if(getImageViewFrom("../res/0.PNG") != null){
      gp.add(getImageViewFrom("../res/0.PNG"));
  }else{
      //No agrega imagen.
  }
    
answered by 13.09.2018 в 19:33