【问题标题】:JavaFX - Making GridPane take up all available space in BorderPaneJavaFX - 使 GridPane 占用 BorderPane 中的所有可用空间
【发布时间】:2015-01-28 11:38:13
【问题描述】:

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

    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 方法之类的东西,但运气不佳。

【问题讨论】:

  • 正如docs 中所述:如果应用程序需要在有额外空间的情况下增长特定的行或列,它可以设置其增长优先级RowConstraintsColumnConstraints 上(滚动到行/列大小调整)。他们在文档中有一个示例。创建约束对象并将它们添加到窗格中

标签: java user-interface javafx


【解决方案1】:

对不起,我误解了这个问题。

按钮太小了,所以没有占用边框窗格中的所有空间?按钮的宽度取决于它所具有的文本的大小。你只需在里面写一个数字,这样它们就很小了。使用 button.setPrefWidth(Integer.MAX_VALUE) 他们会使用他们能得到的所有宽度!

【讨论】:

  • 将其更改为 (int row = 0; row
  • 您可以按照您喜欢的任何顺序将节点添加到GridPane
【解决方案2】:

您的GridPane 已经占用了所有可用空间,即整个Borderpane。它的 GridCells 没有使用 GridPane 可用的空间。

您可以利用 GridPane 中的HgrowVgrow 选项来使单元格占据整个可用空间。

这是一个使用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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多