How do I make a mouse click event be acknowledged by a TreeItem in a TreeView?

∥☆過路亽.° 提交于 2019-11-27 09:54:05

Register a mouse listener with each tree cell, using a cell factory. I don't know the data type you have in your TreeView, but if it were String it might look something like this:

// Controller class:
public class MainWindowUi {

    @FXML
    private TreeView<String> traceTree ;

    // ...

    public void initialize() {
        traceTree.setCellFactory(tree -> {
            TreeCell<String> cell = new TreeCell<String>() {
                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty) ;
                    if (empty) {
                        setText(null);
                    } else {
                        setText(item);
                    }
                }
            };
            cell.setOnMouseClicked(event -> {
                if (! cell.isEmpty()) {
                    TreeItem<String> treeItem = cell.getTreeItem();
                    // do whatever you need with the treeItem...
                }
            });
            return cell ;
        });
    }

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