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

前端 未结 1 877
南笙
南笙 2020-12-02 03:16

The fxml file is as follows (headers omitted):



        
相关标签:
1条回答
  • 2020-12-02 03:33

    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 ;
            });
        }
    
        // ... 
    }
    
    0 讨论(0)
提交回复
热议问题