Search code examples
javauitableviewjavafxtableview

How to get the selected TableView using multiple TableViews


I'm building a timetable with javafx and I'm using 5 TableViews, each of them for one day of the week (Monday - Friday). I want to delete a item from a TableView with a Button. It is no problem for me to delete a Item from one specific TableView. But I want the Button to work for all the TableViews.

So my question is: Is there a method to get the selected TableView? Not just the selected Item from one TableView.

@FXML public void fachLoeschen() {
    TableView<Fach> tableview = new TableView<Fach>();
    //tableview = the TableView in which the selected Item is
        
    int selectedIdx = tableview.getSelectionModel().getSelectedIndex();
    if (selectedIdx==-1)return;
    Fach fach = tableview.getSelectionModel().getSelectedItem();
    var alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure you want to delete: "+fach.getFach()+ " ?", ButtonType.YES, ButtonType.NO);
    if (alert.showAndWait().orElse(ButtonType.NO) == ButtonType.YES) tableview.getItems().remove(selectedIdx);
}

this is the code for the Method. The word 'fach' (i'm german) stands for the course that is put in the Timetable.


Solution

  • You can track which table view last had focus:

    private TableView<Fach> currentFocusedTable ;
    
    // ...
    public void initialize() {
    
        // existing code...
    
        for (TableView<Fach> table : listOfAllTables) {
            table.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
                if (isNowFocused) {
                    currentFocusedTable = table ;
                }
            });
        }
    
    }
    

    And then:

    @FXML public void fachLoeschen() {
    
        if(currentFocusedTable == null) return ;
    
        int selectedIdx = currentFocusedTable.getSelectionModel().getSelectedIndex();
        if (selectedIdx==-1)return;
        Fach fach = currentFocusedTable.getSelectionModel().getSelectedItem();
        var alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure you want to delete: "+fach.getFach()+ " ?", ButtonType.YES, ButtonType.NO);
        if (alert.showAndWait().orElse(ButtonType.NO) == ButtonType.YES) currentFocusedTable.getItems().remove(selectedIdx);
    }