r/JavaFX • • Nov 08 '24

Help column setOnEditStart does not get trigger sometimes, why?

I'm working with two columns, let's call them Column A and Column B. When I finish editing Column A, I want to press Tab to jump to Column B, and I expect Column B's setOnEditStart to be triggered. However, it only triggers sometimes. Why is that?

First, I define Column B's setOnEditCommit:

javaCopy codecolumnB.setOnEditStart((CellEditEvent<tableEntry, String> event) -> { 
    // Does not get triggered sometimes.
});

Then, I set up Column A with a custom CellFactory to handle the Tab key press:

javaCopy codecolumnA.setCellFactory(col -> { 
    TextFieldTableCell<tableEntry, String> cell = new TextFieldTableCell<>(new DefaultStringConverter());
    
    cell.addEventFilter(KeyEvent.KEY_PRESSED, event -> { 
        if (event.getCode() == KeyCode.TAB) { 
            event.consume(); 
            
            Platform.runLater(() -> { 
                int rowIndex = cell.getIndex(); 
                cell.requestFocus();
                
                // Allow the UI thread to process any remaining events
                Platform.runLater(() -> { 
                    int currentIndex = cell.getTableView().getColumns().indexOf(cell.getTableColumn()); 
                    int nextIndex = currentIndex + 2; // Assuming this moves focus to *Column B*
                    logService.info("Next index is: " + nextIndex, true); 
                    
                    cell.getTableView().edit(rowIndex, cell.getTableView().getColumns().get(nextIndex)); 
                }); 
            }); 
        } 
    }); 
    
    return cell; 
});

---

This setup sometimes skips triggering Column B's `setOnEditStart`. Does anyone know why this might be happening? Is there a better approach to ensure `setOnEditStart` always triggers when moving to the next column?

2 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/tonyz0212 Nov 08 '24

Yes, that is correct. Pressing TAB should move to the next editable cell horizontally. Could you provide a reference or example on how to do this by subscribing to cell focus?

I read some posts on Stack Overflow about moving to the next cell, and they use getTableView().edit.( where I pass in the ROW index and column it should go to) However, I am not sure how subscribing to the focus should work.

1

u/SpittingBull Nov 08 '24

From JFX 21 on I think every property like focusProperty() have a subscribe() method that allows you to attach a Consumer which will be invoked whenever the property changes.

So it's something like

cell.focusProperty().subscribe(isFocused->{if (isFocused) edit...});