按钮之间有无法解释的空间

0 java javafx

我做运动有问题。场景中的第一个按钮和第二个按钮之间有无法解释的空间。我更改了按钮的位置,但第一个按钮与第二个按钮之间有一个空格。是什么原因造成的?如何缩小此空间? https://imgur.com/hYolYE2

    public void start(Stage myStage) {

        GridPane myPane = new GridPane();
        myPane.setPadding(new Insets(10, 10, 10, 10));
        myPane.setHgap(10);
        myPane.setVgap(10);

        Button btn1 = new Button("Computer Scinence");
        Button btn2 = new Button("Chemistry");
        Button btn3 = new Button("Arts");

        DrawText txt1 = new DrawText("Computer Scince","Times Roman",FontWeight.BOLD,FontPosture.ITALIC,20,Color.GREEN);
        DrawText txt2 = new DrawText("Chemistry","Times Roman",FontWeight.BOLD,FontPosture.ITALIC,20,Color.BLUE);
        DrawText txt3 = new DrawText("Arts","Times Roman",FontWeight.BOLD,FontPosture.ITALIC,20,Color.YELLOW);

        GridPane.setConstraints(btn1,0,1);
        GridPane.setConstraints(btn2,1,1);
        GridPane.setConstraints(btn3,2,1);
        GridPane.setConstraints(txt1,0,2);
        GridPane.setConstraints(txt2,0,3);
        GridPane.setConstraints(txt3,0,4);

        myPane.getChildren().addAll(btn1,btn2,btn3,txt1,txt2,txt3);

        Scene myScene = new Scene(myPane,350,190);        
        myStage.setScene(myScene);        
        myStage.setTitle("Exercise 3_3");        
        myStage.show();
    }

Run Code Online (Sandbox Code Playgroud)

Zep*_*hyr 6

您通常可以GridPane通过打开网格线来调试布局问题:

myPane.setGridLinesVisible(true);
Run Code Online (Sandbox Code Playgroud)

重新创建应用程序后(您没有包括您的DrawText类,因此我只是在对Labels进行样式设置),然后打开网格线就会发现问题所在:

屏幕截图1

你可以看到,计算机科学 LabelGridPane位置0, 1比更大的宽度计算机科学 Button。这会导致GridPane扩大第一列的宽度以容纳Label

您有两种选择来解决此问题,具体取决于您希望布局如何工作。

1)设置列跨度

如果您要保持Computer Science Button的大小不变,但第一列的宽度不能扩展为适合Label,则Label跨度为2列:

GridPane.setColumnSpan(txt1, 2);
Run Code Online (Sandbox Code Playgroud)

屏幕截图2

2)增加按钮宽度

如果您想扩展计算机科学 Button以填充本专栏的其余部分,可以将其MaxWidth属性设置为使用最大值:

btn1.setMaxWidth(Double.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)

屏幕截图3