我是JavaFX的新手。有谁知道我如何在屏幕中间垂直放置两个按钮(彼此下面)。
到目前为止,这是我的代码:
public class StartMenu {
private StackPane gridStartMenu;
private Button createNewTournamentbtn;
private Button viewTournamentbtn;
private Scene startMenuScene;
private VBox vboxStartMenu;
public StartMenu() {
gridStartMenu = new StackPane();
vboxStartMenu = new VBox();
//BUTTON 1
createNewTournamentbtn = new Button("Create new tournament");
createNewTournamentbtn.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
createNewTournamentbtn.setPrefSize(300, 50);
//BUTTON 2
viewTournamentbtn = new Button("View tournaments");
viewTournamentbtn.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
viewTournamentbtn.setPrefSize(300, 50);
gridStartMenu.setAlignment(createNewTournamentbtn, Pos.CENTER);
gridStartMenu.setAlignment(viewTournamentbtn, Pos.CENTER);
gridStartMenu.getChildren().addAll(createNewTournamentbtn,
viewTournamentbtn);
startMenuScene = new Scene(gridStartMenu, 600, 600);
MainApp.getWindow().setScene(startMenuScene);
MainApp.getWindow().show();
最佳答案
一个好建议:不要过多地依赖Scenebuilder或类似的东西。如果您真的想学习JavaFX,请完全自己编写代码。
这是您可以做的事情:
首先,在VBox中添加两个按钮:
VBox vbox = new VBox(5); // 5 is the spacing between elements in the VBox
vbox.getChildren().addAll(new Button("Button 1"), new Button("Button 2"));
然后,使用以下代码将VBox居中:
stackPane.getChildren().add(vbox);
StackPane.setAlignment(vbox, Pos.CENTER);
stage.setScene(new Scene(stackPane));
stage.show();