The Unfun Cat The Unfun Cat - 5 months ago 20
Java Question

Populating a tableview with strings

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.

Answer

Yeah, it was simple you dummy. Create a Row-class:

Row(String fName, String fValue){
    this.fieldName = new SimpleStringProperty(fName);
    this.fieldValue = new SimpleStringProperty(fValue);
}

For each row in the String-array you create a row-object which you add to an observableList.

private ObservableList<Row> observableList = FXCollections.observableArrayList(          
              new Row("The Unfun Cat", "Is a terrible programmer"), 
              new Row("Stack Overflow", "Rules!");

Then you create a tablecolumn for both columns in the array.

TableColumn columnName = new TableColumn("Name");
columnName.setCellValueFactory(
        new PropertyValueFactory<Row,String>("fieldName"));

(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.