Javafx Treeview item action event

南楼画角 提交于 2019-11-28 22:08:16
tarrsalah

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.

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);
    }
}

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