Как ограничить узлы, добавленные в 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);
}
Поэтому к элементам управления, которые я добавляю, привязаны методы, которые будут изменять масштаб всех меток при изменении размера элемента управления. Это работало нормально, когда они были просто на сцене или сцене, но теперь это не сработает, потому что они просто игнорируют ограничения, и я не уверен почему. Я не мог найти пример, который продемонстрировал бы, что мне нужно было сделать. Я проверил здесь и последовал примеру, но это тоже не сработало. Итак... что я здесь делаю не так? Есть ли лучший способ добиться результатов, к которым я стремлюсь?
1 ответ
Хорошо, так что все, что я сделал, было правильно. Проблема, с которой я столкнулся, заключалась в том, что пользовательские элементы управления Minimum size и Maximum size были установлены неправильно. Чтобы это работало (в будущем, если кто-то столкнется с этим, вряд ли), убедитесь, что ваш минимальный размер (X и Y) и ваш максимальный размер (опять же) установлены соответствующим образом.