Marcarrelus Marcarrelus - 3 months ago 31
Java Question

JavaFX - TableView - Populate cell with text from multiple properties

I think this isn't such a hard problem, but I can't get my head around it. Basiclly it gets down to this:

I have a TableView that is populated with objects from the model class Foo:

class Foo {
private StringProperty textColA;
private StringProperty textColB1;
private StringProperty textColB2;

// Getters, setters and properties left away
}


The first column just gets it's data from the
textColA
StringProperty. Column B on the other hand needs both the data from
textColB1
and
textColB2
. Is it possible to create some sort of property that wraps these two?

Answer

Sure. For example, to produce a concatenation of the two strings with a space between, do

TableColumn<Foo, String> someColumn = new TableColumn<>("Column");
someColumn.setCellValueFactory(cellData -> Bindings.createStringBinding(() ->
    cellData.getValue().getTextColB1() + " " + cellData.getValue().getTextColB2(),
    cellData.textColB1Property(), cellData.textColB2Property()));

(more simply in this particular case, you could do

someColumn.setCellValueFactory(cellData ->
    cellData.getValue().textColB1Property().concat(" ")
        .concat(cellData.getValue().textColB2Property());

but the more general form will work for arbitrary functions of the two properties).

Comments