【发布时间】:2019-03-09 11:49:05
【问题描述】:
我正在尝试制作一个充满按钮的 JavaFX GridPane。我有一个带有对象的 ArrayList,对于每个对象,都需要制作一个按钮。但是,ArrayList 的大小并不总是相同的。因此,我到目前为止制作了这段代码:
JavaFX GridPane 部分:
<AnchorPane fx:id="gridAnchorPane" minHeight="120.0" minWidth="450.0" prefHeight="120.0" prefWidth="550.0">
<GridPane fx:id="peopleGridPane" hgap="5.0" layoutX="98.0" layoutY="43.0" translateX="1.0" translateY="1.0" translateZ="1.0" vgap="5.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
</GridPane>
</AnchorPane>
如您所见,我的行和列为零,因为我打算将它们设为动态数量和大小。
制作按钮的控制器部分:
int GRIDWIDTH = //how many buttons are to fit in one row
for (int i = 0; i < people.size(); i++){
peopleGridPane.add(personButton(people.get(i).getName()), i % GRIDWIDTH, i / GRIDWIDTH);
}
private Button personButton(String name) {
button.setPrefSize(
peopleGridPane.getWidth() / GRIDWIDTH,
peopleGridPane.getHeight() / (people.size() / GRIDWIDTH)
);
使用这种方法,我遇到了两个问题。
- 当我的“人”少于三个时,我的网格如下所示
- 当我启动应用程序时,网格如下所示
我很茫然,所以欢迎所有建议。
对于问题2,我做了一个简单的复盘:
主要:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
控制器:
private int GRIDWIDTH = 3;
@FXML
@Override
public void initialize(URL location, ResourceBundle resources) {
refresh();
}
private void refresh() {
for (int i = 0; i < people.size(); i++) {
Button button = new Button(people.get(i).getName());
button.setPrefSize(
grid.getWidth() / GRIDWIDTH,
grid.getHeight() / (people.size() / GRIDWIDTH)
);
button.setOnAction(event -> refresh());
grid.add(button, i % GRIDWIDTH, i / GRIDWIDTH);
}
}
public Controller() {
people = new ArrayList<>();
people.add(new Person("P1"));
people.add(new Person("P2"));
people.add(new Person("P3"));
people.add(new Person("P4"));
}
.fxml 文件:
<SplitPane dividerPositions="0.5" orientation="VERTICAL" prefHeight="201.0" prefWidth="240.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<items>
<Pane prefHeight="200.0" prefWidth="200.0" />
<GridPane fx:id="grid" alignment="center" hgap="10" vgap="10">
</GridPane>
</items>
</SplitPane>
点击按钮之前。
点击按钮后。
【问题讨论】:
-
@kleopatra 我添加了一些链接。
-
请edit您的问题包含实际的代码示例。不推荐链接到代码...
-
@Zephyr 代码示例是什么?
-
@Luctia - 您正在链接到代码。不要那样做。阅读上面 kleopatra 发布的链接并相应地更新您的问题。
-
@Zephyr 我想人们会想自己测试一下。现已添加。
标签: java for-loop javafx size gridpane