如何使TreeView中的TreeItem确认鼠标单击事件?
fxml文件如下(标题省略):
我可以毫无问题地设置TreeView
的根目录。 树更新没有问题。
我遇到的问题是我无法设法在视图中的给定项目上触发事件。 我尝试用一个简单的System.out.println()添加一个onMouseClicked
事件,我可以看到事件被触发,无论我在树中单击哪个项目。 但我无法设法获取视图中单击的项目。
我怎么做?
使用单元工厂为每个树单元注册一个鼠标侦听器。 我不知道你在TreeView
的数据类型,但如果它是String
它可能看起来像这样:
// Controller class: public class MainWindowUi { @FXML private TreeView traceTree ; // ... public void initialize() { traceTree.setCellFactory(tree -> { TreeCell cell = new TreeCell () { @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 treeItem = cell.getTreeItem(); // do whatever you need with the treeItem... } }); return cell ; }); } // ... }