Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Friday, April 15, 2016

A Utility Method for Edit Commits in a JavaFX TableView

I found it difficult to string together a long statement involving casting to retrieve a TableRow's backing object in a JavaFX TableView, so I wrote this method.

static <T, S> T getObjectAtEvent(CellEditEvent<T, S> evt) {
 TableView<T> tableView = evt.getTableView();
 ObservableList<T> items = tableView.getItems();
 TablePosition<T,S> tablePosition = evt.getTablePosition();

 int rowId = tablePosition.getRow();
 T obj = items.get(rowId);

 return obj;

This method is for working with JavaFX Controller objects like these

TableColumn<MyObject,Number> tcId;
TableColumn<MyObject,String> tcData;

TableView<MyObject> tblObjects;

Where MyObject is a POJO with id and data fields.

The getObjectAtEvent() method can be used in the Edit Commit handler for the TableColumn.

tcData.setCellValueFactory(new PropertyValueFactory<MyObject,String>("data"));  
tcData.setOnEditCommit((evt) -> {

 MyObject obj = getObjectAtEvent(evt);  // <--- APPLYING THE METHOD

 if( !dirtyFlag.get() ) {
 String oldData = obj.getData();
 obj.setData( evt.getNewValue() );
 updateList.add( new UpdateObject(obj.getId(), obj.getData(), oldData));

No comments:

Post a Comment