【发布时间】:2017-12-12 06:41:18
【问题描述】:
我的目标是创建一个可调整大小、始终为正方形且包含相等数量的行和列的 GridView,使它们的单元格也为正方形,类似于黑白棋或国际象棋棋盘。
这是一个小插图,网格在内容窗格中水平居中。
我尝试了多种不同的绑定变体和布局,但我不能完全正确。这是我的控制器(到目前为止):
public class Controller {
public HBox contentPane;
public void initialize() {
final int sideLength = 10;
final GridPane gridPane = new GridPane();
gridPane.setStyle("-fx-border-color: red; -fx-border-insets: 2");
HBox.setHgrow(gridPane, Priority.ALWAYS);
for (int i = 0; i < sideLength; i++) {
final ColumnConstraints columnConstraints = new ColumnConstraints(Control.USE_PREF_SIZE, 10, Double.MAX_VALUE);
columnConstraints.setHgrow(Priority.ALWAYS);
gridPane.getColumnConstraints()
.add(columnConstraints);
final RowConstraints rowConstraints = new RowConstraints(Control.USE_PREF_SIZE, 10, Double.MAX_VALUE);
rowConstraints.setVgrow(Priority.ALWAYS);
gridPane.getRowConstraints()
.add(rowConstraints);
}
contentPane.getChildren().add(gridPane);
for (int i = 0; i < sideLength; i++) {
for (int j = 0; j < sideLength; j++) {
final GameCell child = new GameCell();
GridPane.setRowIndex(child, i);
GridPane.setColumnIndex(child, j);
gridPane.getChildren().add(child);
}
}
}
}
还有那些应该包含 Shapes 的单元格,但我现在只是 Circles 只是为了测试它:
public class GameCell extends VBox {
private final Circle circle;
public GameCell() {
circle = new Circle();
setMinSize(0, 0);
setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE);
getChildren().add(circle);
final ChangeListener<Number> listener = (observable, oldValue, newValue) ->
circle.setRadius((int) (Math.min(this.getWidth(), this.getHeight()) / 2));
widthProperty().addListener(listener);
heightProperty().addListener(listener);
}
}
这是目前的样子:
【问题讨论】:
标签: java layout javafx gridpane