2017-05-03 91 views
0

好吧,我得到了這個javafx應用程序,我得到了鍛鍊,我可以通過肌肉組過濾它們,但是當它未經過濾的程序從obseravable列表中刪除對象並從tableView中刪除時,從tableview中,但對象仍然存在。所以下次我過濾它的背部。只從Tableview中刪除不observableList

這裏是我的observableLists

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); 
} 

這裏是remove方法

@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); 
} 

任何人都得到了解決,爲什麼它不會刪除對象

+0

你應該得到您'deleteExercise'方法的例外,因爲當你通過它迭代不能修改的列表。爲什麼不使用預定義的['FilteredList'](http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/FilteredList.html)類? –

+0

我不能讓FilteredList工作 – novafluff

回答

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); 
}