Reputation: 12178
All the examples I've found over the web, about manipulating the data inside a TableView widget of JavaFX, were using an API that was not ever common for Table widgets in GUI libraries (Model class, Observable lists and such...).
Is there a simple way to use this table widget, i.e. without a model class?
I would be very glad if there were simple methods, like:
table.getModel().setValue(rowIndex, colIndex, someData);
table.addEmptyRow(index);
Is there anything like this in JavaFX?
Upvotes: 1
Views: 160
Reputation: 209225
You can always just make a TableView<Object[]>
. Then
table.getModel().setValue(rowIndex, colIndex, someData);
table.addEmptyRow(index);
just become
table.getItems().get(rowIndex)[colIndex] = someData ;
table.getItems().add(new Object[numColumns]);
respectively. (Or similar code for a TableView<List<Object>>
, if you prefer.)
Just more as a comment: I think in almost all cases (whatever toolkit you use), having a model class for the table rows makes things simpler than the old Swing style, which the above code emulates. The problem with this style is that your code loses all the semantics of what you're actually displaying. The only exceptions might be something like a general database (or CSV/tab-delimited file) viewer.
Update
This approach will only work if the data are not going to change while the table is displayed, and if you set all the data before you display it. This is because the TableView
uses JavaFX observable properties to get notifications of changes to the data.
You could sort of modify it as follows:
TableView<List<ObjectProperty<Object>>> table = new TableView<>();
Then adding a new row becomes
table.getItems().add(IntStream.range(0, numCols)
.mapToObj(colIndex -> new SimpleObjectProperty<>())
.collect(Collectors.toList());
and setting a value becomes
table.getItems().get(rowNumber).get(columnNumber).set(someValue);
At this point, it almost certainly becomes easier to use the API the way it was intended, and create a model class for the row items.
Upvotes: 1