Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda operator in TableColumn:: setOnEditCommit()

I use TableView in my code. I want to make cells editable. I found sample on Oracle site that works excellent

lastNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
lastNameCol.setOnEditCommit(
    new EventHandler<CellEditEvent<Person, String>>() {
       @Override
       public void handle(CellEditEvent<Person, String> t) {
            ((Person) t.getTableView().getItems().get(
                t.getTablePosition().getRow())
                ).setLastName(t.getNewValue());
        }
    }
);

Then I decided to use lambda operator instead of anonymous class.

lastNameCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());
lastNameCol.setOnEditCommit(
    (CellEditEvent<Person, String> t) -> {
            ((Person) t.getTableView().getItems().get(
                    t.getTablePosition().getRow())
                    ).setLastName(t.getNewValue());
    });

I got compiler error.

Incompatible types: incompatible parameter types in lambda expression

But I found this sample on Oracle site too.

Perhaps this problem is widely known but I didn’t find solution. Why is this code wrong?

like image 625
Yura Avatar asked Apr 21 '26 11:04

Yura


1 Answers

It looks like you have declared the table column as a raw type:

TableColumn lastNameCol = new TableColumn(...);

You should not do this (your IDE really should give you a warning here). Use properly parameterized types:

TableColumn<Person, String> lastNameCol = new TableColumn<>(...);

Now, since the compiler knows the type of the column, the lambda will work. Additionally, you can get rid of the cast to Person:

lastNameCol.setOnEditCommit(
    (CellEditEvent<Person, String> t) -> {
        t.getTableView().getItems().get(
                t.getTablePosition().getRow())
                .setLastName(t.getNewValue());
});

Notice that CellEditEvent has a getRowValue() that you can use:

lastNameCol.setOnEditCommit((CellEditEvent<Person, String> t) ->
    t.getRowValue().setLastName(t.getNewValue()));

or you can take complete advantage of type inference with

lastNameCol.setOnEditCommit(t ->
    t.getRowValue().setLastName(t.getNewValue()));
like image 124
James_D Avatar answered Apr 23 '26 01:04

James_D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!