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

时间:2019-03-23 14:17:50

标签: 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();
    }

1 个答案:

答案 0 :(得分:6)

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

myPane.setGridLinesVisible(true);

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

screenshot 1

您可以看到,Label位置GridPane上的计算机科学 0, 1的宽度大于计算机科学 { {1}}。这导致Button扩展第一列的宽度以容纳GridPane

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

1)设置列跨度

如果您要保持 Computer Science Label的大小不变,但是第一列的宽度不能扩展到适合Button的大小,则只需将{{1 }}跨2列:

Label

screenshot 2

2)增加按钮宽度

如果您想扩展计算机科学 Label来填充该列的其余部分,则可以将其GridPane.setColumnSpan(txt1, 2); 属性设置为使用最大值:< / p>

Button

screenshot 3

相关问题