mynameisJEFF
mynameisJEFF

Reputation: 4239

JavaFX: How to select and delete multiple objects in TableView

How can I select and delete multiple objects in TableView ?

public class Controller implements Initializable{
    public TableView<Student> fxClassroom;
    public void deleteStudent(){
        ObservableList<Student> studentSelected, allStudents;
        allStudents = fxClassroom.getItems();
        studentSelected = fxClassroom.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        studentSelected.forEach(allStudents::remove);
    }
}

But in eclipse, I kept getting this error:

Type mismatch cannot convert void to ObservableList

Upvotes: 0

Views: 2235

Answers (3)

NaveenBharadwaj
NaveenBharadwaj

Reputation: 1333

fxClassroom.setSelectionMode(SelectionMode.MULTIPLE);

This enables you to select multiple rows in the table.

ObservableList<Student> list = fxClassroom.getSelectionModel().getSelectedItems();
fxClassroom.getItems().removeAll(list);

Upvotes: 0

PekosoG
PekosoG

Reputation: 264

First you have to enable Multiple Selection on your Table

myTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

This will enable to the user to select multiple items using the Ctrl key.

Then, in the Event of your "Delete" button, you have to do something like this:

ObservableList<MyDisplayedObject> SelectedItemsOfTable=tblProductos.getSelectionModel().getSelectedItems();

if(SelectedItemsOfTable.size()>0){
   //Do your Stuff here
}

Where "MyDisplayedObject" is the class of the objects you're displaying on your TableView.

Upvotes: 1

Kachna
Kachna

Reputation: 2961

Try this:

 public class Controller implements Initializable{
    public TableView<Student> fxClassroom;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
      ....
    fxClassroom.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
      ....
    }

        public void deleteStudent(){
            ObservableList<Student> studentSelected, allStudents;
            allStudents = fxClassroom.getItems();
            studentSelected = fxClassroom.getSelectionModel().getSelectedItems();
            allStudents.removeAll(studentSelected);


        }
    }

Upvotes: 1

Related Questions