Khanjee Khanjee - 1 month ago 4x
Java Question

How to implement drag drop of multiple rows in TreeTableView/TableView?

I found an example of drag drop for treetableview but it works for just one row. I couldn't find any help for drag drop of multiple rows in treetableview or tableview. Any help would be appreciated.

Example of single row drag drop


All you need to do to modify allow dragging of multiple rows in your example is to put an array of data into the clipboard instead of just the data. So in the example you linked, you would do like this instead:

row.setOnDragDetected(event -> {
   if (!row.isEmpty()) {
      Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
      db.setDragView(row.snapshot(null, null));
      ClipboardContent cc = new ClipboardContent();

      // Here you provide the ClipboardContent instance with the selected indexes instead of just one index.
      cc.put(SERIALIZED_MIME_TYPE, new ArrayList<Integer>(getSelectionModel().getSelectedIndices()));

Then you would just have to handle all of those indexes in the setOnDragDropped method:

row.setOnDragDropped(event -> {
   Dragboard db = event.getDragboard();
   if (acceptable(db, row)) {
       // Get all indexes.
       ArrayList<Integer> indexes = (ArrayList<Integer>) db.getContent(SERIALIZED_MIME_TYPE);

       ObservableList<TreeItem> items = FXCollections.observableArrayList();    
       // Get the item on each index.
       for (int index : indexes) {

       // Modify the rest of the code commented out below to remove 
       // all items in your list and then add them your target.
       // item.getParent().getChildren().remove(item);
       // getTarget(row).getChildren().add(item);
       // event.setDropCompleted(true);
       // tree.getSelectionModel().select(item);


Of course, you will have to enable multiple selection in your table to begin with. This is done by doing table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);.