如何使用JavaFX将图像设置为背景?

问题描述 投票:1回答:2

我正在尝试将图像作为背景放在JavaFX场景中,但我的代码不起作用。

我试图在java eclipse中制作战舰游戏程序,但我遇到了图形问题。

公共类WindowGUI扩展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
        }
    });


}

}

当我第一次尝试运行它时,它工作并打开一个新窗口,中间有一个按钮,但是bakcground是空白的。当我尝试在窗口中将图像设置为背景时,忽略“开始”按钮,没有任何反应..

java javafx
2个回答
3
投票

更好的方法是使用Background类,而不是尝试添加ImageView作为你的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);

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.