1
votes

Newbie to javafx, and i am currently unable to get my image to become my background, its probably something silly. Here's the code. Any help appreciated.

package game;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import javafx.scene.layout.Pane;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.Background;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundPosition;
public class appgame extends Application {

    Button button;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Title of the Window");
        Pane p = new HBox();
        p.setPadding(new javafx.geometry.Insets(5,5,5,5));
        Image image = new Image("file:/home/rex/Documents/codes/java/bg1.jpg");

BackgroundImage backgroundImage = new BackgroundImage(image,BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize);

Background background = new Background(backgroundImage);

        Scene scene = new Scene(p, 306, 460);

        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

I am unable to connect my background to my scene, please some one help me set my image as my scene background. Currently the code only shows a blank stage, without the background image. Thanks in advance.

1

1 Answers

1
votes

You forgot to add the background to the instantiated Pane (p).

package appgame;

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

import static javafx.scene.layout.BackgroundPosition.CENTER;
import static javafx.scene.layout.BackgroundRepeat.NO_REPEAT;
import static javafx.scene.layout.BackgroundRepeat.REPEAT;
import static javafx.scene.layout.BackgroundSize.*;

public class AppGame extends Application {

    private static final String BACKGROUND_PATH = "<path to background>";

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane p = new HBox();
        p.setPadding(new javafx.geometry.Insets(5,5,5,5));
        //Set your background!
        p.setBackground(new Background(new BackgroundImage(new Image(BACKGROUND_PATH), REPEAT, NO_REPEAT, CENTER, DEFAULT)));

        primaryStage.setTitle("Title of the Window");
        primaryStage.setScene(new Scene(p, 306, 460));
        primaryStage.show();
    }
}

This results in (using a png on my filesystem):

enter image description here