JavaFX – 使GridPane占用BorderPane中的所有可用空间

我正在使用以下代码为计算器创建一个简单的按钮网格:

    BorderPane rootNode = new BorderPane();

    GridPane gridPane = new GridPane();
    rootNode.setCenter(gridPane);

    int counter = 1;
    for(int row = 3; row > 0; row--)
        for(int col = 0; col < 3; col++) {
            Button button = new Button("" + counter++);
            button.setOnAction(this);
            gridPane.add(button, col, row);
        }
    gridPane.add(new Button("R"), 0, 4);
    gridPane.add(new Button("0"), 1, 4);

(想发布一张它在这里的样子,但我没有足够的声望点可以这么做)

GridPane最终变得很小,并且在左上角塞满了,但我希望它占用BorderPane中心区域的所有可用空间(在这种情况下,这将是整个窗口).我已经尝试过乱搞各种各样的setSize方法,但是运气不好.

最佳答案 您的GridPane已经占用了所有可用空间,即整个Borderpane.它的GridCells没有使用GridPane可用的空间.

您可以使用GridPane中提供的Hgrow和Vgrow选项,使单元占用整个可用空间.

下面是一个使用setHgrow来使用GridPane可用的整个宽度的示例.您可以为高度添加相同的内容.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {
        BorderPane rootNode = new BorderPane();
        rootNode.setMinSize(300, 300);
        rootNode.setStyle("-fx-background-color: RED;");
        GridPane gridPane = new GridPane();
        gridPane.setStyle("-fx-background-color: BLUE;");
        rootNode.setCenter(gridPane);

        int counter = 1;
        for (int row = 3; row > 0; row--)
            for (int col = 0; col < 3; col++) {
                Button button = new Button("" + counter++);
                gridPane.add(button, col, row);
                GridPane.setHgrow(button, Priority.ALWAYS);
            }
        Button r = new Button("R");
        gridPane.add(r, 0, 4);
        GridPane.setHgrow(r, Priority.ALWAYS);
        Button r0 = new Button("0");
        gridPane.add(r0, 1, 4);
        GridPane.setHgrow(r0, Priority.ALWAYS);
        Scene scene = new Scene(rootNode);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
点赞