不确定为什么按钮在Java FX中不会彼此相邻对齐

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

我是Java fx的新手。我正在创建一个基本的GUI,它的外观应如下所示:enter image description here

但是,当我尝试时,我的图像看起来像这样:

enter image description here

我不确定两个按钮之间为何有很大的间隙。我正在使用网格窗格格式。这是我的代码:

public class Main extends Application {
@Override
public void start(Stage stage) {
    //Creating Text field
    TextField textField1 = new TextField();

    //Creating Buttons
    Button submit = new Button("Submit");
    Button cancel = new Button("Cancel");

    //Creating a Grid Pane
    GridPane gridPane = new GridPane();

    //Setting size for the pane
    gridPane.setMinSize(200, 100);

    //Setting the padding
    gridPane.setPadding(new Insets(10, 10, 10, 10));

    //Setting the vertical and horizontal gaps between the columns
    gridPane.setVgap(5);
    gridPane.setHgap(1);

    //Setting the Grid alignment
    gridPane.setAlignment(Pos.CENTER);

    //Arranging all the nodes in the grid
    gridPane.add(textField1, 0, 0);
    gridPane.add(submit, 0, 1);
    gridPane.add(cancel, 1,1);

    //Creating a scene object
    Scene scene = new Scene(gridPane);

    //Setting title to the Stage
    stage.setTitle("Simple Form");

    //Adding scene to the stage
    stage.setScene(scene);

    //Displaying the contents of the stage
    stage.show();
}
public static void main(String args[]){
    launch(args);
}

}

将不胜感激:-)

java user-interface javafx gridpane
2个回答
0
投票

这里发生的是,您的TextField设置在左上角(0,0),但仅跨越一列。您可以看到位于右下角(1,1)的cancel Button从TextField停止的位置开始(如果仅查看x位置)。

GridPanes有一个调试选项,因此您可以直观地了解发生了什么。只需致电

gridPane.setGridLinesVisible(true):

解决方案是将TextField设置为获取/跨越2列。您可以通过以下方式进行操作:

GridPane.setColumnSpan(textField1, 2);

或使用其他add方法:

gridPane.add(textField1, 0, 0, 2, 1);

有关网格窗格如何工作的更多信息,请参见https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/GridPane.html


0
投票

快速回答:取消按钮在新列中。

TexField和Submit按钮位于同一字段中,因此它们在垂直方向上对齐。您可以使用以下命令显示GridPane的行:

gridPane.setGridLinesVisible(true);  

并且在您运行应用程序时,您会看到类似以下内容的内容:

---------------------  
|TextField |        |
|Submit    | Cancel |
---------------------

您可以使TextField使用以下两列:

gridPane.add(textField1, 0, 0, 2, 1);

摘自文档:add(节点子级,整数columnIndex,整数rowIndex,整数colspan,整数rowpan)使用Scene Builder将有助于您更轻松地理解它。

© www.soinside.com 2019 - 2024. All rights reserved.