我是JavaFX的新手,我想创建一个包含一些列和行的Grid示例。网格如下: -第一行:第一个单元格(宽度= 100)占据1列,第二个单元格(宽度= 200)占据2列 -第二行:第一个(宽度= 200)单元格占用2列,第二个(宽度= 100)单元格占用1列
但是我不知道为什么会出现意外的单元格。如下图:
我的代码如下:
// Label 1
Label lbl1 = new Label("Label1");
lbl1.setPrefWidth(100);
lbl1.setStyle("-fx-border-style: solid; -fx-background-color: #80aaff; -fx-border-width: 0.25");
// Label 2
Label lbl2 = new Label("Label2");
lbl2.setStyle("-fx-border-style: solid; -fx-background-color:#ff80bf; -fx-border-width: 0.25");
lbl2.setPrefWidth(200);
// Label 3
Label lbl3 = new Label("Label3");
lbl3.setPrefWidth(200);
lbl3.setStyle("-fx-border-style: solid; -fx-background-color:#66ff99; -fx-border-width: 0.25");
// Label 4
Label lbl4 = new Label("Label4");
lbl4.setPrefWidth(100);
lbl4.setStyle("-fx-border-style: solid; -fx-background-color: #ffff66; -fx-border-width: 0.25");
GridPane gridPane = new GridPane();
gridPane.setStyle("-fx-border-style: solid");
// column 0, row 0, column span 1, row span 1
gridPane.add(lbl1, 0, 0, 1, 1);
// column 1, row 0, column span 2, row span 1
gridPane.add(lbl2, 1, 0, 2, 1);
// column 0, row 1, column span 1, row span 1
gridPane.add(lbl3, 0, 1, 2, 1);
// column 2, row 1, column span 2, row span 1
gridPane.add(lbl4, 2, 1, 1, 1);
谁能指出我的问题? 谢谢。
答案 0 :(得分:1)
使用列跨度/重叠列的GridPane
的首选宽度的计算通常无法按预期方式进行。您看到的“单元格”是GridPane
未被任何孩子覆盖的背景。
为避免GridPane
太大,请通过ColumnConstraints
设置列宽:
// Label 1
Label lbl1 = new Label("Label1");
lbl1.setMaxWidth(Double.MAX_VALUE);
lbl1.setStyle("-fx-border-style: solid; -fx-background-color: #80aaff; -fx-border-width: 0.25");
// Label 2
Label lbl2 = new Label("Label2");
lbl2.setStyle("-fx-border-style: solid; -fx-background-color:#ff80bf; -fx-border-width: 0.25");
lbl2.setMaxWidth(Double.MAX_VALUE);
// Label 3
Label lbl3 = new Label("Label3");
lbl3.setMaxWidth(Double.MAX_VALUE);
lbl3.setStyle("-fx-border-style: solid; -fx-background-color:#66ff99; -fx-border-width: 0.25");
// Label 4
Label lbl4 = new Label("Label4");
lbl4.setMaxWidth(Double.MAX_VALUE);
lbl4.setStyle("-fx-border-style: solid; -fx-background-color: #ffff66; -fx-border-width: 0.25");
GridPane gridPane = new GridPane();
ColumnConstraints constraints = new ColumnConstraints(100);
gridPane.getColumnConstraints().addAll(constraints, constraints, constraints);
gridPane.setStyle("-fx-border-style: solid");
// column 0, row 0, column span 1, row span 1
gridPane.add(lbl1, 0, 0);
// column 1, row 0, column span 2, row span 1
gridPane.add(lbl2, 1, 0, 2, 1);
// column 0, row 1, column span 1, row span 1
gridPane.add(lbl3, 0, 1, 2, 1);
// column 2, row 1, column span 2, row span 1
gridPane.add(lbl4, 2, 1);
但是,这并不能防止在调整窗口大小时再次出现空白的“空格”。要对所有列使用相同的大小,而不考虑GridPane
的宽度,请使用percentWidth
:
ColumnConstraints constraints = new ColumnConstraints();
constraints.setPercentWidth(100d/3d);
gridPane.setPrefWidth(300);