我正在尝试将图像作为背景放入 JavaFX 场景中,但我的代码无法正常工作。
我试图在 java eclipse 中制作战舰游戏程序,但我遇到了图形问题。
公共(public)类 WindowGUI 扩展应用程序{
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
}
});
}
当我第一次尝试运行它时,它成功了,并且打开了一个新窗口,中间有一个按钮,但是后台是空白的。当我尝试将图像设置为窗口中的背景时,在“开始”按钮后面,没有任何反应..
最佳答案
更好的方法是使用 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);
关于java - 如何使用 JavaFX 将图像设置为背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55635045/