1

I'm trying to put an image as a background in a JavaFX scene, but my code isn't working.

Im trying to make a Battleship-game program in java eclipse but i'm stuck at a graphics problem.

public class WindowGUI extends Application{

Game game;
Image image;

public WindowGUI(Game game) {
    this.game = game;
}

public static void main(String[] args) {
    Game game = new Game();
    new WindowGUI(game);
}

@Override
public void start(Stage stage) throws Exception {

    stage.setTitle("Battleship");
    image = new Image ("C:\\Users\\amali\\git\\inf101.v19.sem2\\inf101.v19.sem2\\src\\window\\battleshipbackground.jpg");
    ImageView background = new ImageView(image);
    Button startButton = new Button("START");
    BorderPane newStack = new BorderPane();
    newStack.getChildren().add(startButton);
    newStack.getChildren().add(background);
    stage.setScene(new Scene(newStack, 1300, 860));
    stage.show();

    startButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
        //  START THE GAME
        }
    });


}

}

When I first tried to run it, it worked and a new window opened with a button in the center, but the bakcground was blank. When i try setting an image as background in the window, behing the 'start'-button, nothing happens..

Mampenda
  • 661
  • 4
  • 21
  • Observe the [`Image.exception`](https://openjfx.io/javadoc/12/javafx.graphics/javafx/scene/image/Image.html#exceptionProperty()) property to see if there are any errors trying to load the image. – Slaw Apr 11 '19 at 17:50

2 Answers2

3

A better way to do it is to use the Background class rather than trying to add an ImageView as a child of your BorderPane.

Image image = new Image("C:\\Users\\amali\\git\\inf101.v19.sem2\\inf101.v19.sem2\\src\\window\\battleshipbackground.jpg");

BackgroundSize size = new BackgroundSize(BackgroundSize.AUTO, 
        BackgroundSize.AUTO, 
        false, 
        false, 
        true, 
        false);

Background background = new Background(new BackgroundImage(image,
        BackgroundRepeat.NO_REPEAT,
        BackgroundRepeat.NO_REPEAT,
        BackgroundPosition.CENTER,
        size));

newStack.setBackground(background);
Matt
  • 2,063
  • 1
  • 14
  • 35
0

Use BackgroundImage class. or try this JavaFX How to set scene background image

Mujtaba
  • 349
  • 1
  • 4
  • 17