JavaFX callback lambda expression
So I'm trying to update the old JavaFX application I created on the Java 6 release I got a hint that I can convert the current code and use lambda expressions. Can someone help me convert this code here or guide me in some way?
// define a simple boolean cell value for the action column so that the column will only be shown for non-empty rows. addColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<UserDetails,Boolean>,ObservableValue<Boolean>>() { @Override public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<UserDetails,Boolean> features) { return new SimpleBooleanProperty(features.getValue() != null); } }); // create a cell value factory with an add button for each row in the table. addColumn.setCellFactory(new Callback<TableColumn<UserDetails,TableCell<UserDetails,Boolean>>() { @Override public TableCell<UserDetails,Boolean> call(TableColumn<UserDetails,Boolean> personBooleanTableColumn) { return new AddPersonCell(window,tableUser); } });
Solution
Lambda expressions are valid only if there is an abstract method in the interface Since this is a callback situation, this can be a
Basically, you put the anonymous class in the form of lambda expression (< parameters >) – > < method body >
under these circumstances
new Callback<TableColumn.CellDataFeatures<UserDetails,ObservableValue<Boolean>>() { @Override public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<UserDetails,Boolean> features) { return new SimpleBooleanProperty(features.getValue() != null); } }
change
(TableColumn.CellDataFeatures<UserDetails,Boolean> features) -> { return new SimpleBooleanProperty(features.getValue() != null); }
This can further simplify:
>If you do not need parameter types to determine the methods to call, you can delete them. > If only one parameter has no type, you can delete () parentheses. > If the method body contains only one statement, {} and; Can be deleted If the statement is a return statement, you also need to delete the return keyword
This allows you to further simplify lambda expressions
features -> new SimpleBooleanProperty(features.getValue() != null)
Use the same method
new Callback<TableColumn<UserDetails,Boolean>>() { @Override public TableCell<UserDetails,Boolean> personBooleanTableColumn) { return new AddPersonCell(window,tableUser); } }
Can be changed to
personBooleanTableColumn -> new AddPersonCell(window,tableUser)