2

I'm curious if there is a way to bind a JavaFX Label's textProperty() to a TableViews's selectedItemProperty() without getting a NullPointerException when no entry is selected, which is for example during initialization.

Here is a little snippet to illustrate the actual situation:

@FXML
private Label l_name;
@FXML
TableView<TableEntry> tv_table;

l_name.textProperty().bind(tv_table.selectedItemProperty().get().getName());

The get() can only return an object of type TableEntry when an item is selected, which is not the case during execution of the initialize() method in my controller class. So the code throws a NullPointerException trying to execute getName() on the actual "tablerow".

What is the best solution for this problem? At the moment I've implemented a ChangeListener on the selectedItemProperty(), which than changes the labels text by calling setText() directly. But this feels a little bit more complicated then it should be.

Richard
  • 582
  • 5
  • 19
  • 2
    A `ChangeListener` is probably the easiest way to go. You can use a select: `l_name.textProperty().bind(Bindings.selectString(tv_table.getSelectionModel().selectedItemProperty(), "name");`. This will generate warning messages when the selected item is null, but will still work. Otherwise, you can use a third party binding library ([ReactFX](https://github.com/TomasMikula/ReactFX) has this [functionality](http://www.reactfx.org/javadoc/2.0-M5/org/reactfx/value/Val.html#selectVar-javafx.beans.value.ObservableValue-java.util.function.Function-), for example). – James_D Jun 05 '17 at 21:10

0 Answers0