How to pass a variable to a method in button clickListener event?

191 Views Asked by At

I have a button with a ClickListener event and a method inside. The method is responsible for adding a new row in Vaadin GirdLayout once a button is clicked.

private GridLayout buildDeductionsGrid(){
        GridLayout deductionsGrid = new GridLayout(13, 8);

        deductionsGrid.setSpacing(true);
        deductionsGrid.setWidth("50%");

        addDeductionsGridLabelsAndFields(deductionsGrid);

        return deductionsGrid;
    }

This method creates a grid for rows to be inserted.

private void addDeductionsGridLabelsAndFields(GridLayout deductionsGrid) {
    int rowIndex = 1;

    btnAddDeductionRow.addClickListener((Button.ClickListener) event -> addNewDeductionRow(deductionsGrid, rowIndex));
}

rowIndex as it's name suggests is index of a row which needs to be incremented in addNewDeductionRow method. It increments without a problem the first time the button is clicked but it doesn't save the incrementation so when the button is clicked the second time, it tries to add a row at the same place when the button was clicked first.

private void addNewDeductionRow(GridLayout deductionsGrid, int rowIndex) {
        String cbValue = deductionTypeDropdown.getValue().toString().toLowerCase();

        for (DeductionsGridRow deductionsGridRow : deductionsGridRows) {
            if (deductionsGridRow.getDeductionType().getName().toLowerCase().equals(cbValue)) {
                deductionsGrid.addComponent(deductionsGridRow.getGridRowLabel(), 0, rowIndex);

                deductionsGrid.addComponent(new Label("Amount"), 1, rowIndex);
                deductionsGrid.addComponent(deductionsGridRow.getAmount(), 2, rowIndex);
            }
        }
        rowIndex++;
    }

This method does what it says - adds a new row.

Note: deductionsGrid and rowIndex are marked as final; I am using Vaadin 7.6.2

1

There are 1 best solutions below

1
On

It seems your always passing 1 as the rowIndex into your function. The incrementation inside the function does not change the value outside of the function (and even if it would, 'outside' it is just another variable with local scope)

Maybe try to determine the rowIndex dynamically using GridLayout#getRows.

EDIT after comment

If the getRows() function always returns the predetermined grid size, then maybe the GridLayout itself is the problem here. It seems that it is intended to be used for laying out given content. When you are creating/changing content dynamically a list or table or some iterating component may be the right tool here