0

I'm trying to set an image as the background of GridPane. I do not use fxml code so plain JavaFX code.

    public Login()  {
        grid = new GridPane();
        grid.setAlignment (Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25,25,25,25));


        Image img = new Image("/src/application/Images/L.png");
        ImageView imgView = new ImageView(getClass().getResource("/src/application/Images/L.png").toExternalForm());
        imgView.setImage(img);
        grid.getChildren().addAll(imgView);
        scene = new Scene (grid, 300, 150);

The exception boils down to this snippet

> Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found

How do I fix this issue?

Paul
  • 25
  • 6
  • Please just look at the stacktrace because the error stands right there `Invalid URL or resource not found` so basically the Url to the image cannot be found. Please look at [this](https://stackoverflow.com/questions/26973860/how-open-image-with-url-in-javafx) – fuggerjaki61 Nov 11 '19 at 21:01
  • Does this answer your question? [Imageview in Javafx : Invalid URL](https://stackoverflow.com/questions/29670013/imageview-in-javafx-invalid-url) – fuggerjaki61 Nov 11 '19 at 21:05
  • You have the `/src` in the request. It is unlikely that your build output directory include `/src`, as the build output is usually just required resource and binaries, not source. Have a look at your build output directory and check for the location of `L.png` (or even if it is in the build output directory at all). If the build output is a jar rather than a directory, then run `jar tvf ` and see if and where `L.png` is stored in the jar. – jewelsea Nov 11 '19 at 21:10
  • 1
    I removed src and it works, but the image isn't a background ;( – Paul Nov 11 '19 at 21:29
  • You haven't created a background and [set it on a Region](https://openjfx.io/javadoc/13/javafx.graphics/javafx/scene/layout/Region.html#setBackground(javafx.scene.layout.Background)) (you could also do that through CSS rather than API if you prefer, see the [`-fx-background-*`](https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#region) properties for region in the CSS reference guide). Or you could create the background by layering nodes in a StackPane, there are a few different ways. – jewelsea Nov 11 '19 at 21:37

1 Answers1

2

I removed src from the image path to get:

Image img = new Image("/application/Images/L.png");    

and I added:

grid.setBackground(
    new Background(
       new BackgroundImage(
           img, 
           BackgroundRepeat.REPEAT, 
           BackgroundRepeat.REPEAT, 
           BackgroundPosition.DEFAULT, 
           BackgroundSize.DEFAULT
       )
    )
);

and it works.

jewelsea
  • 150,031
  • 14
  • 366
  • 406
Paul
  • 25
  • 6