Search code examples
javafxfxmlgridpane

JavaFX: Organize controls in rows (in gridpane) using FXML


I have a GUI with a lot controls (Labels, Textfields, Comboboxes and Checkboxes). I organize them in a Gridpane and would like to have them in rows and columns (like it is intended with gridpane layout).

If I use FXML I write it like this:

<GridPane>
   <Label GridPane.rowIndex="0" GridPane.columnIndex="0" text="field1"/>
   <TextField GridPane.rowIndex="0" GridPane.columnIndex="1"/>
   <Label GridPane.rowIndex="1" GridPane.columnIndex="0" text="field2"/>
   <TextField GridPane.rowIndex="1" GridPane.columnIndex="1"/>
</GridPane>

Now the issue: If I would like to add a row between row 0 and 1, I need to increase the row index of the following row. Now lets take 20 rows and 5 columns, where I would like to add a row after the first one. This would create a big afford for me to increase the rownumber for every row below the first one.

Is there something like a row-element which positions its child controls in the same row with increasing column numbers? I think of something like this:

<GridPane>
   <GridPane.Row>
       <Label text="field1"/>
       <TextField/>
   </GridPane.Row>
   <GridPane.Row>
       <Label text="field2"/>
       <TextField/>
   </GridPane.Row>
</GridPane>

I do know of the VBox and HBox, which is pretty much what I want, but I want to have the elements in columns with fixed width.


Solution

  • You can use an object to track rowIndex.

    Java:

    public class RowCounter {
        private int currentRowIndex = 0;
    
        /**
         * Return current rowIndex.
         * @return
         */
        public int getCr() {
            return currentRowIndex;
        }
    
        /**
         * Return current rowIndex and increase it.
         * @return
         */
        public int getNr() {
            return currentRowIndex++;
        }
    }
    

    FXML:

    <GridPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
        <fx:define>
            <RowCounter fx:id="rc" />
        </fx:define>
    
        <children>
            <Label text="Name:" GridPane.columnIndex="0" GridPane.rowIndex="$rc.cr" />
            <TextField GridPane.columnIndex="1" GridPane.rowIndex="$rc.nr" />
    
            <Label text="Age:" GridPane.columnIndex="0" GridPane.rowIndex="$rc.cr" />
            <TextField GridPane.columnIndex="1" GridPane.rowIndex="$rc.nr" />
    
            <Label text="Address:" GridPane.columnIndex="0" GridPane.rowIndex="$rc.cr" />
            <TextField GridPane.columnIndex="1" GridPane.rowIndex="$rc.nr" />
        </children>
    </GridPane>