Robb1
Robb1

Reputation: 5025

How to change number of rows of a GridPane programmatically?

I'm new to JavaFX and I'm trying to create a GridPane with fixed number of columns but variable number of rows (according to how many elements I want to insert in my view).

I prepared the fxml relative to each element all inside a VBox.

The result I would like to obtain is something like this

+---+  +---+  +---+
|   |  |   |  |   |
+---+  +---+  +---+

+---+  +---+  +---+
|   |  |   |  |   |
+---+  +---+  +---+

+---+  +---+  
|   |  |   |  
+---+  +---+  

With number of elements varying according to how many elements I have in my database.

How to insert custom elements in a GridPane

How to make its number of rows programmatically changeable?

Upvotes: 2

Views: 2891

Answers (2)

user1409784
user1409784

Reputation:

Just to show a general approach that you could implement in a larger code base

If we create the following as variables

private final GridPane grid = new GridPane();

private Item[][] items;
private int columnCount = 0;
private int rowCount = 0;

below is a method that will update a grid pane using set column and row index methods

/**
 * Should be called whenever items array changes.
 */
private void render() {

    List<Item> toAdd = new ArrayList<>();
    for (int column = 0; column < columnCount; column++) {
        for (int row = 0; row < rowCount; row++) {
            Item item = getItemAt(column, row);

            // if it is null it wont be painted e.g. empty/blank item
            if (item != null) {
                toAdd.add(item);
                GridPane.setColumnIndex(item, item.getColumn());
                GridPane.setRowIndex(item, item.getRow());
            }
        }
    }

    // add all at once for better performance
    grid.getChildren().setAll(toAdd);
}

here is a gist for the rest of the class https://gist.github.com/nsavageJVM/5775128a9682ebcf0e8186ff209f4f8e

Upvotes: 0

DVarga
DVarga

Reputation: 21799

You can use GridPane#addRow(int, Node...)

AtomicInteger rowCount = new AtomicInteger();
GridPane gp = new GridPane();
gp.setGridLinesVisible(true);
Button b = new Button("Add Row");
b.setOnAction( e-> gp.addRow(rowCount.getAndIncrement(),
        new Label("Row" + (rowCount.get()-1) + " Col1"),
        new Label("Row" + (rowCount.get()-1) + " Col2")));

Each Node in the vararg argument will be placed into a new column.

Upvotes: 1

Related Questions