[英]JavaFX - BorderPane is not centered in scene/stage
我目前正在編寫一個棋盤游戲,我正在使用 java 和用於 GUI 目的的 javaFX。該游戲需要 map(游戲板)位於屏幕中間,並且各種選項和附加信息位於它周圍。 我的想法是有一個 BorderPane,其中中心節點是游戲板,頂部、底部等是附加選項。
我的問題是,在啟動應用程序時,BorderPane 不在舞台中央,而是稍微擴展到右側和底部,在那里它不可見。 因此看不到我的底部節點。 奇怪的是,如果我最小化 window 並再次最大化它,一切都在它應該在的地方並且完全在舞台的范圍內。
我的中心節點是一個普通的窗格。 我也做 stage.setMaximize(true)。 因此 window 在啟動應用程序時已經最大化,再次最小化和最大化應該沒有什么不同。
這個場景的代碼基本上可以歸結為:
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
Pane pane = createGameBoard();
pane.setId("mapPane");
Button button = new Button("Save");
VBox box = new VBox(0, button);
box.setAlignment(Pos.CENTER);
Label label = new Label("Bottom");
label.setPrefHeight(20);
BorderPane borderPane = new BorderPane();
borderPane.setTop(top);
borderPane.setBottom(bottom);
borderPane.setCenter(center);
borderPane.setPadding(new Insets(10));
Scene scene = new Scene(borderPane);
scene.getStylesheets().add(Objects.requireNonNull(MainGUI.class.getResource("/game.css")).toString());
stage.setScene(scene);
}
game.css 樣式表目前只設置背景顏色。 我正在使用:Java 17、JavaFX 17。
如果您需要任何進一步的信息,我很樂意提供:)
謝謝!
編輯:要重現我的問題,請運行此代碼。 單擊“下一個屏幕”按鈕后,應該會出現該問題。
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class App extends Application {
private Stage stage;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
stage.setTitle("App");
stage.setMinHeight(600);
stage.setMinWidth(800);
stage.setWidth(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth());
stage.setHeight(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getHeight());
stage.setMaximized(true);
stage.setOnCloseRequest(e -> System.exit(0));
Button button = new Button("Next Screen");
button.setOnAction(e -> {gameScreen();});
BorderPane borderPane = new BorderPane();
borderPane.setCenter(button);
Scene scene = new Scene(borderPane);
stage.setScene(scene);
stage.show();
}
private void gameScreen() {
Circle circle = new Circle(0, 0, 4);
Pane pane = new Pane(circle);
pane.setStyle("-fx-background-color: #00c3ff");
Button button = new Button("Top");
VBox vBox = new VBox(0, button);
vBox.setAlignment(Pos.CENTER);
Label label = new Label("Bottom");
BorderPane borderPane = new BorderPane();
borderPane.setTop(vBox);
borderPane.setCenter(pane);
borderPane.setBottom(label);
borderPane.setPadding(new Insets(10));
Scene scene = new Scene(borderPane);
stage.setScene(scene);
}
}
我的問題是通過更改我正在使用的場景的根解決的,而不是在每次切換布局(例如從主菜單到游戲屏幕)時都創建一個新場景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.