what is the correct way to add EventHander to a TableCell?
at first I only had these two lines
@FXML private TableColumn EANCol;
...
EANCol.setCellValueFactory(new PropertyValueFactory<MyRow, String>("EAN"));
and everything worked until I tried adding an event
EventHandler eh = new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){
if(mouseEvent.getClickCount() == 2){
System.out.print("Double clicked ");
System.out.println(mouseEvent.getTarget().toString());
}
}
}
};
EANCol.setCellFactory(new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn p) {
TableCell cell = new TableCell();
cell.setOnMouseClicked(eh);
return cell;
}
});
Problem: now I can double click on it, but the whole column is empty, with null as value.
A table cell created with the default constructor doesn't actually do anything in its updateItem(...)
method to cause anything to be displayed. There is a DEFAULT_CELL_FACTORY
defined in TableColumn
that represents a factory generating "default" table cells (i.e. displaying the string version of the content). So if you want the default behavior with an event handler added you can do:
EANCol.setCellFactory(new Callback<TableColumn<?,?>, TableCell<?,?>>() {
@Override
public TableCell call(TableColumn<?,?> p) {
TableCell<?,?> cell = TableColumn.DEFAULT_CELL_FACTORY.call(p);
cell.setOnMouseClicked(eh);
return cell;
}
});