ScrollPane中的JavaFX GridPane比预期的要大

时间:2017-11-11 02:19:53

标签: java javafx scrollpane gridpane

当我在弄javafx时,我遇到了这样的事情:
我创建了一个GridPane,将其包裹在ScrollPane中并填充了Buttons,但事先更改了RowConstraintsColumnConstraints {。}}。 />
问题是水平滚动条看起来不合适。我相信它是GridPane那么胖,但它是怎么发生的呢? This is what i'm getting when running the code.

但垂直滚动条非常好。

GridPane

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

1 个答案:

答案 0 :(得分:1)

您为每一行添加了列列约束,这意味着最终您将拥有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中删除这些约束。