如何在代码中约束添加到GridPane的节点?

时间:2014-07-27 23:57:12

标签: constraints javafx-8 gridpane

我需要在代码中将自定义JavaFX控件添加到网格窗格。 我设置了网格窗格的行和列约束,如下所示:

//These are doubles for the purposes of calculating more accurate percentages, see below.
//I feel like there should be a better way to accomplish this but I only want 5
//players per row, so the number of columns would be between 1 and 5 depending on the
//number of players, but if there are 5 or more, modulus doesn't work (5 % 5 = 0)... 
//I'm really bothered by this bit but it was the best I could devise.
double ColumnCount = Math.min(5, this.Settings.PlayerCount());
//This I feel fine with.
double RowCount = this.Settings.PlayerCount() / 5;

//The method encapsulating this code is for starting a new game. 
//This bit is for capturing player names for reassignment.
ArrayList<String> Names = new ArrayList<>();
if (this.Players.size()> 0)
    this.Players.stream().forEach((EQLPlayer plr) ->
        Names.add(plr.PlayerName())
    );

//This is for clearing the fields so they can be repopulated appropriately.
this.Players.clear();
this.gpPlayerField.getChildren().clear(); //<---- gpPlayerField is the GridPane with which I am working that I am trying to populate.
this.gpPlayerField.getColumnConstraints().clear();
this.gpPlayerField.getRowConstraints().clear();

//This bit is for setting up the Column and Row constraints.
for (int x = 0; x < ColumnCount; x++){
    ColumnConstraints CC = new ColumnConstraints();
    CC.setMaxWidth(200.00);
    CC.setPercentWidth( 100.00 / ColumnCount );
    CC.setHgrow(Priority.ALWAYS);
    this.gpPlayerField.getColumnConstraints().add(CC);
}
for (int x = 0; x < RowCount; x++){
    RowConstraints RC = new RowConstraints();
    RC.setMaxHeight(100.00);
    RC.setPercentHeight( 100.00 / RowCount );
    RC.setVgrow(Priority.ALWAYS);
    this.gpPlayerField.getRowConstraints().add(RC);
}

这是问题所在(我认为,代码的其余部分是因为我错过了一些愚蠢明显的东西。

//I really feel like this should be working but it isn't.
//I want the rows and columns constrained to the size of the GridPane 
//(which is constrained to the stage) so that they will grow and shrink with it, but
//they are pretty much ignoring it.
for (int x = 0; x < this.Settings.PlayerCount(); x++){
    EQLPlayer plr = new EQLPlayer(x + 1);
    plr.GameMode(this.Settings.Mode());
    if (x < Names.size()) plr.PlayerName(Names.get(x));
    this.gpPlayerField.add(plr, x % 5, x / 5);
    GridPane.setHgrow(plr, Priority.ALWAYS);
    GridPane.setVgrow(plr, Priority.ALWAYS);
}

因此,我添加的控件具有绑定到它们中的方法,这些控件将在控件大小更改时重新缩放所有标签。当它们只是在舞台或场景上时,它工作得很好,但现在它不会起作用,因为它们只是忽略了约束,我不确定为什么。我无法找到一个证明我需要做什么的例子。我检查了here并按照示例进行了操作,但这也没有效果。那么......我在这里做错了什么?有没有更好的方法来实现我正在寻找的结果?

1 个答案:

答案 0 :(得分:1)

好吧,所以我所做的一切都是正确的。 我遇到的问题是自定义控件最小尺寸和最大尺寸未正确设置。 为了使这项工作(在不太可能的情况下,任何人遇到此事),确保你的最小尺寸(X和Y)和你的最大尺寸(再次)设置得恰当。