Is drag and drop supported by TreeItem?

这一生的挚爱 提交于 2019-12-21 12:00:13

问题


I'm currently working with a JavaFx-2's TreeView representing a file system.

I want to enable drag and drop to allow move operations, but it looks like TreeItem doesn't include drag events listeners. I was only able to implement drag and drop on the englobing TreeView object, but it doesn't work for sub-items.

Am I missing something, or are drag and drop events not supported for TreeItems yet?


回答1:


Question answered by Csh on the Oracle Forums : https://forums.oracle.com/forums/message.jspa?messageID=10426066#10426066

You have to implement drag on drop on the TreeCell.

Write a CellFactory like this:

TreeView<String> treeView = new TreeView<String>();
    treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
        @Override
        public TreeCell<String> call(TreeView<String> stringTreeView) {
            TreeCell<String> treeCell = new TreeCell<String>() {
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null) {
                        setText(item);
                    }
                }
            };

            treeCell.setOnDragDetected(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {

                }
            });

            return treeCell;
        }
    });

If he wants to claim his reputation or add information to his solution, I'll change this answer.




回答2:


The answer by @Timst is correct, but you should change the "updateItem" method cause in the above case you wont be able to set the Graphic of the "TreeItem" and the tree collapse won't work properly (won't clear the text in subNodes).

just change the method to:

@Override
protected void updateItem(String item, boolean empty) {
    super.updateItem(item, empty);
    if (!empty && item != null) {
        setText(item);
        setGraphic(getTreeItem().getGraphic());
    }else{
        setText(null);
        setGraphic(null);
    }
}


来源:https://stackoverflow.com/questions/11242847/is-drag-and-drop-supported-by-treeitem

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