Javafx Treeview item action event

前端 未结 4 1977
小蘑菇
小蘑菇 2020-12-09 07:06

I\'m trying to create a menu using a treeView. This is the first time I\'m using treeView and have been reading up on it on several websites.

I\'m having some proble

相关标签:
4条回答
  • 2020-12-09 07:30

    I couldn't find method getPickResult in mouse event, so maybe next is preferable then answer from Alex:

    1) add listener to tree view

    treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> handle(newValue));
    

    2) handle clicks, it's not need distinguish clicks on empty space and nodes

    private void updateSelectedItem(Object newValue) {      
        System.out.println(newValue);
    }
    
    0 讨论(0)
  • 2020-12-09 07:32

    According to the JavaFX 2.2 documentation :

    " ..a TreeItem is not a Node, and therefore no visual events will be fired on the TreeItem, To get these events, it is necessary to add relevant observers to the TreeCell instances (via a custom cell factory)."

    I think this example on using TreeView will be somehow useful.

    0 讨论(0)
  • 2020-12-09 07:37
    treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
    
                    @Override
                    public void changed(ObservableValue<? extends TreeItem<String>> observable,
                            TreeItem<String> oldValue, TreeItem<String> newValue) {
                        // newValue represents the selected itemTree
                    }
    
                });
    
    0 讨论(0)
  • 2020-12-09 07:47

    This may be solved by implementing CellFactory, but I think the easiest way is like this:

    1) Create and add an event handler to the TreeView:

    EventHandler<MouseEvent> mouseEventHandle = (MouseEvent event) -> {
        handleMouseClicked(event);
    };
    
    treeView.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEventHandle); 
    

    2) Handle only clicks on the nodes (and not on empy space os the TreeView):

    private void handleMouseClicked(MouseEvent event) {
        Node node = event.getPickResult().getIntersectedNode();
        // Accept clicks only on node cells, and not on empty spaces of the TreeView
        if (node instanceof Text || (node instanceof TreeCell && ((TreeCell) node).getText() != null)) {
            String name = (String) ((TreeItem)treeView.getSelectionModel().getSelectedItem()).getValue();
            System.out.println("Node click: " + name);
        }
    }
    
    0 讨论(0)
提交回复
热议问题