仅从Tableview中删除而不是observableList

时间:2017-05-03 11:43:56

标签: java javafx tableview observablelist

好吧,我得到了这个javafx应用程序,我得到了练习,我可以通过肌肉群过滤它们但是当它未经过滤时,我的程序从obseravable列表和tableView中删除了对象但是当它被过滤时它只从tableview中删除但是对象仍然存在。所以下次我过滤它的背面。

以下是我的可观察列表

ObservableList<Exercise> filteredExercises = FXCollections.observableArrayList();
 ObservableList<Exercise> exercises = FXCollections.observableArrayList();

这是过滤方法

  @FXML
private void filterByChest(ActionEvent event) {
    filteredExercises.clear();
    for (Exercise xercise : exercises) {
        System.out.println(xercise);

        if(xercise.getFocusGroup().toLowerCase().contains("chest")){
            filteredExercises.add(new Exercise(xercise.getName(), xercise.getFocusGroup(), xercise.getTool(), xercise.getPb()));
        }
    }
       exTable.setItems(filteredExercises);
}

这是删除方法

 @FXML
private void deleteExercise(ActionEvent event) {
Exercise selectedItem = exTable.getSelectionModel().getSelectedItem();
for (Exercise e : exercises){
    if(selectedItem == e){
       exercises.remove(e);
    }
}
exTable.getItems().remove(selectedItem);
    System.out.println(exercises);
}

任何人都能解决为什么它不会删除对象

1 个答案:

答案 0 :(得分:2)

您应该使用FilteredList来实现此功能:

// create the lists:
ObservableList<Exercise> exercises = FXCollections.observableArrayList();

// initialize the filtered list with a filter that is always true 
// (i.e. no filtering)
ObservableList<Exercise> filteredExercises = exercises.filtered(exercise -> true);

// use the filtered list as the items list for the table:
public void initialize() {
    // ...

    exTable.setItems(filteredExercises);

    // ...
}

// filter by setting the predicate on the filtered list:
@FXML
private void filterByChest(ActionEvent event) {
    filteredExercises.setPredicate(
        exercise -> exercise.getFocusGroup().toLowerCase().contains("chest"));
}

// manipulate the list by adding/removing elements to/from the underlying list:
@FXML
private void deleteExercise(ActionEvent event) {
    Exercise selectedItem = exTable.getSelectionModel().getSelectedItem();
    exercises.remove(selectedItem);
}