繁体   English   中英

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

[英]JavaFX - Making GridPane take up all available space in 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可用的空间。

您可以使用Vgrow提供的HgrowVgrow选项,使单元占用整个可用空间。

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

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);
    }
}

对不起,我很想念这个问题。

按钮太小了,所以不占用边框中的所有空间? 按钮的宽度取决于其具有的文本大小。 你只需在其中写一个数字,这样它们就相当小了。 使用button.setPrefWidth(Integer.MAX_VALUE),他们使用他们可以获得的所有宽度!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM