JavaFX的GridPane在ScrollPane中是大于预期
当我和javafx
瞎搞,我以前遇到过这样一件事:
我创建了一个GridPane
,包裹在一个ScrollPane
和充满Buttons
,但改变RowConstraints
和ColumnConstraints
为预先提供GridPane
。
问题是水平滚动条看起来不足。我相信这是一个GridPane
胖,但它是怎么发生的?
但是,垂直滚动条是完美的。JavaFX的GridPane在ScrollPane中是大于预期
sample.fxml
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SampleController">
<children>
<ScrollPane AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<content>
<GridPane fx:id="gridPane" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
</GridPane>
</content>
</ScrollPane>
</children>
</AnchorPane>
sampleController.java
public class SampleController {
@FXML public GridPane gridPane;
@FXML
public void initialize(){
RowConstraints rowConstraints = new RowConstraints(10.0, 40, 40);
ColumnConstraints columnConstraints = new ColumnConstraints(10.0, 40, 40);
int i=0,j=0;
for(i=0; i<50; i++){
gridPane.getRowConstraints().add(i, rowConstraints);
for(j=0; j<30; j++) {
gridPane.getColumnConstraints().add(j, columnConstraints);
Button btn = new Button(Integer.toString(j+1));
btn.setPrefSize(40, 40);
gridPane.add(btn, j, i);
}
}
}
}
Dashboard.java
public class sample extends Application{
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene scene = new Scene(root, 300, 275);
stage.setTitle("FXML Welcome");
stage.setScene(scene);
stage.show();
}
}
您要添加的列列约束的每一行,这意味着最终你将有50 * 30 = 1500
限制而不是30
。您需要在行循环之外的循环中添加列约束。此外,假设约束列表在您添加约束之前为空,则不需要指定要插入的索引,因为add
也会插入到List
的末尾。请检查,如果你真的需要在FXML创建列约束,因为代码变得简单一点,如果你不需要插入列约束作为列表的倒数第二个元素:
for (int i = 0; i < 30; i++) {
gridPane.getColumnConstraints().add(columnConstraints);
}
for(int i = 0; i < 50; i++){
gridPane.getRowConstraints().add(rowConstraints);
for(int j = 0; j < 30; j++) {
Button btn = new Button(Integer.toString(j + 1));
btn.setPrefSize(40, 40);
gridPane.add(btn, j, i);
}
}
BTW:请注意,AnchorPane
约束对不是AnchorPane
子节点的节点没有任何影响;您可以安全地从fxml中的GridPane
中删除这些约束。
>如果您确实需要在fxml中创建列约束,请检查。
确实,我不需要它。它是由SceneBuilder创建的,我认为它是无用的。真的,事实并非如此。我已经从fxml和控制器中删除了所有'col/rowConstraints'实例,现在一切正常 –
Quipex
摆脱RowConstraints和ColumnConstraints。你不需要它们。 – VGR