Drag & Drop in JavaFX table?

ε祈祈猫儿з 提交于 2021-01-28 02:01:42

问题


I am using a JavaFX 2 table for some kind of playlist and I want to be able to drag & drop rows in the table, e.g. drag row 3 before row 2, like the drag & drop stuff you know from the playlists in typical media players like e.g. Winamp, AIMP...

Is that possible? Any code samples for that? Thank you very much!


回答1:


try this one :)

@FXML
TableView<String> tableView;
private  ObservableList<String> tableContent = FXCollections.observableArrayList();

//...

tableView.setOnMouseClicked(new EventHandler<MouseEvent>() { //click
            @Override
            public void handle(MouseEvent event) {
                    if(event.getClickCount()==2){ // double click

                        String selected =   tableView.getSelectionModel().getSelectedItem();
                        if(selected !=null){
                            System.out.println("select : "+selected);
                           ...
                        }
                    }
            }
    });

tableView.setOnDragDetected(new EventHandler<MouseEvent>() { //drag
        @Override
        public void handle(MouseEvent event) {
            // drag was detected, start drag-and-drop gesture
            String selected = tableView.getSelectionModel().getSelectedItem();
            if(selected !=null){

                Dragboard db = tableView.startDragAndDrop(TransferMode.ANY);
                ClipboardContent content = new ClipboardContent();
                content.putString(selected);
                db.setContent(content);
                event.consume(); 
            }
        }
    });

tableView.setOnDragOver(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                // data is dragged over the target 
                Dragboard db = event.getDragboard();
                if (event.getDragboard().hasString()){
                    event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                }
                event.consume();
            }
        });

tableView.setOnDragDropped(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                Dragboard db = event.getDragboard();
                boolean success = false;
                if (event.getDragboard().hasString()) {            

                    String text = db.getString();
                    tableContent.add(text);
                    tableView.setItems(tableContent);
                    success = true;
                }
                event.setDropCompleted(success);
                event.consume();
            } 
        });   


来源:https://stackoverflow.com/questions/12353576/drag-drop-in-javafx-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!