I have read the API and examples, but am unable to understand how to populate a tableview.
Let us say I have a two column String array (String[][]) with "name, value"-pairs. I now simply want to create a tableview which shows the data in two columns, displaying the name in the first and value in the second column for all the rows in the original array.
What have I tried? Nothing, but it seems that you need to create observablelists, one for each column, bind it to its respective column and then add the column to the tableview. But this involves "factories" in all the examples I have seen which is an alien concept to me.
I'm guessing this is simple, but I'm unable to wrap my head around it. Please help.
Yeah, it was simple you dummy. Create a Row-class:
For each row in the String-array you create a row-object which you add to an observableList.
Then you create a tablecolumn for both columns in the array.
(identical for Value)
Then you add the observableList to the tableView with tableView.setItems(observableList) and lastly you call the method tableView.getColumns.addAll(fieldName,fieldValue);
(This makes me wonder ho to do it for the general case where you don't know how many columns is in your original String[][] array? Could the row object have an ArrayList to represent arbitrarily many SimpleStringProperties? How would you connect it to the ValueFactories?)
Ps. if anyone creates a more pedagogical example I'll award their post with the "solved" mark.
Cell Value Factory
For each column in your table, you set/create a Cell Value Factory. Each row has a corresponding object in
tableview.getItems()
. To determine how this object is displayed across the columns, each column uses its own Cell Value Factory. The factories take in the object and return the value to be displayed.Since
String[][]
is an array ofString[]
's, we want the factories to take in aString[]
and return theString
corresponding to its column.Example
Here is an example of creating the Cell Value Factories in this way. It is a little verbose but that can be cleaned up with lambdas! (see Lambdas section).
Result
If you throw this example (via the Source Code), on a Stage, this is what you get.
Lambdas
Java is a little verbose, especially when playing with anonymous classes. Thankfully there are lambdas, which bring a little readability back to Java. Here are the same Cell Value Factories from the example, re-written with lambdas.
Source Code
Here is a stand-alone JavaFX class that uses Cell Value Factories in this way.
[NOTE: The answer to this other StackOverFlow question is another example of this. ]
You can also try this with map without knowing how many columns you'll add to the table! so you can use the map key as the tableview header