kmp
kmp

Reputation: 10865

How to bidirectionally bind to a property of an object set to the selected item property of a table view?

I have a user interface that looks like this:

Example User Interface

And what I want is that when you click on 1 in the table, the text box shows 2 and 3 on the table it shows 4 and that when you type into the text box, the property on the object that the selected row is bound to gets updated.

So I have a collection of objects with two properties (value1 - which goes in the table and value2 which goes in the text box).

Now for the complexity: I want to do this with a bi-directional binding, not an event listener.

Essentially the binding for the text box could be described like so:

Bind the text property to the value2 property of the selected item property of the table view bi-directionally

Is this somehow possible?

I was fiddling around and I got this going but it is not bidirectional, of course (I would expect perhaps to have to supply a second callback to go in the opposite direction):

this.textField.textProperty().bind(         
        Bindings.createStringBinding(() -> {

            if (this.tableView.getSelectionModel().getSelectedItem() == null) {
                return "";
            }

            return String.valueOf(this.tableView.getSelectionModel().getSelectedItem().value2Property().get());
        }, 
        this.tableView.getSelectionModel().selectedItemProperty()));

Here is a complete working example of what I am talking about, if it makes it any clearer:

import java.net.URL;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public final class Program extends Application {

    private static final class SomeSortOfController implements Initializable {

        @FXML private TableView<SomeSortOfObject> tableView;
        @FXML private TableColumn<SomeSortOfObject, Number> value1TableColumn;
        @FXML private TextField textField;

        @Override
        public void initialize(final URL url, final ResourceBundle resourceBundle) {

            this.tableView.setItems(FXCollections.observableArrayList(
                    new SomeSortOfObject(1,2),
                    new SomeSortOfObject(3,4)));

            this.value1TableColumn.setCellValueFactory(c -> c.getValue().value1Property());
            this.value1TableColumn.setEditable(false);

            // Here I need to come up with some sort of binding from the selected item
            // in the table view to the value2 property in the SomeSortOfObject (and
            // vice versa)
        }
    }

    private static final class SomeSortOfObject {

        private final IntegerProperty value1;
        private final IntegerProperty value2;

        public SomeSortOfObject(int value1, int value2) {
            this.value1 = new SimpleIntegerProperty(value1);
            this.value2 = new SimpleIntegerProperty(value2);
        }

        public IntegerProperty value1Property() {
            return this.value1;
        }

        public IntegerProperty value2Property() {
            return this.value2;
        }
    }

    public static void main(final String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/main.fxml"));
        loader.setController(new SomeSortOfController());   
        stage.setScene(new Scene(loader.load(), 200, 100));     
        stage.show();
    }
}

Just to be totally complete, this is the contents of the main.fxml file:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<HBox xmlns="http://javafx.com/javafx/8.0.45" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <TableView fx:id="tableView">
        <columns>
          <TableColumn text="value1" fx:id="value1TableColumn" />
        </columns>
      </TableView>
      <TextField fx:id="textField" />
   </children>
</HBox>

Upvotes: 1

Views: 2915

Answers (1)

James_D
James_D

Reputation: 209225

There's no standard API way to do this. There are a few third party libraries that provide this functionality. Probably the best-known is EasyBind, and it's possible this library may be incorporated into JavaFX in version 9.

Here's an SSCCE using EasyBind:

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.monadic.PropertyBinding;

public class BidirectionalBindingToNestedProperty extends Application {

    private PropertyBinding<String> selectedValue2;

    @Override
    public void start(Stage primaryStage) {
        TableView<Item> table = new TableView<>();
        TableColumn<Item, String> col1 = new TableColumn<>("Value 1");
        col1.setCellValueFactory(cellData -> cellData.getValue().value1Property());

        table.getColumns().add(col1);

        TextField textField = new TextField();
        selectedValue2 = EasyBind
                .monadic(table.getSelectionModel().selectedItemProperty())
                .selectProperty(Item::value2Property);
        textField.textProperty().bindBidirectional(selectedValue2);

        for (int i = 1 ; i <= 40; i+=2) {
            Item item = new Item(String.valueOf(i), String.valueOf(i + 1));
            item.value2Property().addListener((obs, oldValue, newValue) -> 
                System.out.println("Item with value1 = "+item.getValue1() + " changed value2 from "+oldValue+" to "+newValue));
            table.getItems().add(item);
        }

        BorderPane root = new BorderPane(table, null, null, null, textField);

        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static class Item {
        private final StringProperty value1 = new SimpleStringProperty();
        private final StringProperty value2 = new SimpleStringProperty();

        public Item(String value1, String value2) {
            setValue1(value1);
            setValue2(value2);
        }

        public final StringProperty value1Property() {
            return this.value1;
        }

        public final java.lang.String getValue1() {
            return this.value1Property().get();
        }

        public final void setValue1(final java.lang.String value1) {
            this.value1Property().set(value1);
        }

        public final StringProperty value2Property() {
            return this.value2;
        }

        public final java.lang.String getValue2() {
            return this.value2Property().get();
        }

        public final void setValue2(final java.lang.String value2) {
            this.value2Property().set(value2);
        }


    }

    public static void main(String[] args) {
        launch(args);
    }
}

Upvotes: 1

Related Questions