非常感谢我对问题的一些帮助。
我正在使用JavaFX和NetBeans IDE。 我正在为桌面客户端创建一个非常简单的启动窗口。 窗口目前看起来像这张图片。
当前看:
想要看(涂上油漆):
换句话说,我希望按钮为:
我目前的设置是:
我有一个GridPane作为根。不确定为什么JavaFX选择使用(col,row),但这就是我将如何代表我的设置:
相关代码(或我认为相关的代码,如果我错了请纠正我)如下:
//adds GridPane to Scene
GridPane grid = new GridPane();
RowConstraints row1 = new RowConstraints();
row1.setPercentHeight(25);
grid.getRowConstraints().add(row1);
grid.setAlignment(Pos.CENTER);
Scene scene = new Scene(grid, 400, 300,Color.WHITESMOKE);
//Create welcome message and add it to grid, and align it to the center
Text sceneTitle = new Text("Welcome");
grid.add(sceneTitle,0,0);
GridPane.setHalignment(sceneTitle,HPos.CENTER);
//Create buttons and fix their widths
Button newBtn = new Button("Create New Project");
Button loadBtn = new Button("Load Existing Project");
newBtn.setMaxWidth(150);
loadBtn.setMaxWidth(150);
//Create a VBox, add children to it, and then add it to the grid
VBox vBtns = new VBox();
vBtns.setSpacing(5);
vBtns.getChildren().addAll(newBtn,loadBtn);
grid.add(vBtns,0,1);
我尝试了很多不同的事情......提到一些更符合逻辑的事情。的:
//1. Center the VBox within its current GridPane cell
GridPane.setHalignment(vBtns,HPos.CENTER);
//2. Center the buttons within the VBox
newBtn.setAlignment(Pos.CENTER);
loadBtn.setAlignment(Pos.CENTER);
我从未擅长GUI编程。当一些应该如此简单的东西需要很长时间才能弄清楚时,这是非常令人沮丧的。 是否有任何开发人员可以帮我找到解决方案?
答案 0 :(得分:1)
要使用当前设置修复它,您只需要:
vBtns.setAlignment(Pos.CENTER);
然而,这似乎过于复杂。为什么不做呢
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class LayoutTest extends Application {
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
RowConstraints row1 = new RowConstraints();
row1.setPercentHeight(25);
grid.getRowConstraints().add(row1);
ColumnConstraints colConstraints = new ColumnConstraints();
colConstraints.setHalignment(HPos.CENTER);
grid.getColumnConstraints().add(colConstraints);
grid.setAlignment(Pos.CENTER);
Scene scene = new Scene(grid, 400, 300,Color.WHITESMOKE);
//Create welcome message and add it to grid, and align it to the center
Text sceneTitle = new Text("Welcome");
sceneTitle.setStyle("-fx-font-size:48;");
grid.add(sceneTitle,0,0);
//Create buttons and fix their widths
Button newBtn = new Button("Create New Project");
Button loadBtn = new Button("Load Existing Project");
newBtn.setMaxWidth(150);
loadBtn.setMaxWidth(150);
grid.add(newBtn, 0, 1);
GridPane.setMargin(loadBtn, new Insets(5, 0, 5, 0));
grid.add(loadBtn, 0, 2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}