gpt4 book ai didi

ScrollPane 中的 JavaFX GridPane 比预期大

转载 作者:行者123 更新时间:2023-12-02 12:01:25 25 4
gpt4 key购买 nike

当我在搞javafx的时候,我遇到过这样的事情:
我创建了一个 GridPane,将其包装在 ScrollPane 中并填充 Buttons,但更改了 RowConstraints事先为 GridPane 设置 ColumnConstraints

问题是水平滚动条看起来不够充分。我相信它是一个如此庞大的 GridPane,但它是如何发生的呢?
This is what i'm getting when running the code.

然而垂直滚动条完全没问题。

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);
}
}

顺便说一句:请注意,AnchorPane 约束对非 AnchorPane 子节点的节点没有任何影响;您可以安全地从 fxml 中的 GridPane 中删除这些约束。

关于ScrollPane 中的 JavaFX GridPane 比预期大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47233711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com