0

I am trying to make an image show up as the background of my scene. Whenever I run the code, it opens the window, but the background is empty. I have tried some of the solutions from here:

JavaFX How to set scene background image

and from here:

Background image in JavaFX

and I could not get either of them to work properly.

import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Starbase extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Starbase Command");
        Pane pane = new Pane();
        ImageView imageView = new ImageView(new Image("file:space.jpg"));
        imageView.setFitHeight(800);
        imageView.setFitWidth(800);
        pane.getChildren().add(imageView);
        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
Emma
  • 27,428
  • 11
  • 44
  • 69
  • I don't advise including the `file:` protocol in the image path. If you package your application into a jar, with the images inside the jar, then the file protocol won't resolve it. Instead, [retrieve the image location as a resource](https://stackoverflow.com/questions/59029879/javafx-image-from-resources-folder). – jewelsea Nov 16 '20 at 19:45

1 Answers1

0

I ended up solving my own question. The following code works as I had originally intended. Honestly not sure why it works this way and not the other, but this is what I have ended up with.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Starbase extends Application {
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
        // Setting the title of the window
        primaryStage.setTitle("Starbase Command");
        //Creating the pane
        StackPane stackPane = new StackPane();
        //Making the imageView for the background
        Image img = new Image("file:space.jpg");
        ImageView imageView = new ImageView(img);
        imageView.setFitHeight(800);
        imageView.setFitWidth(800);
        //Adding the imageView to the stackPane
        stackPane.getChildren().add(imageView);
        Scene scene = new Scene(stackPane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}