How to give an dynamicly loaded TreeViewItem an EventHandler?

一笑奈何 提交于 2019-12-08 09:08:34

问题


at the moment i programm a database based Chat System. The friendlist of every User gets loadet in a TreeView after the login.

means: After the login I request the names of the useres friends by the following Funktion, String namesSt[] = get.getUserFriendNameByUserID(currentUserID);

To use the given Names to load them as TreeItem into my Friendlist / TreeRootItem "rootItem"

for (int counter = 0; counter < namesSt.length; counter++) {
        System.out.println(namesSt[counter]);
        TreeItem<String> item = new TreeItem<String> (namesSt[counter]);

        item.addEventHandler(MouseEvent.MOUSE_CLICKED,handler);

        rootItem.getChildren().add(item);
    }

When I now add my rootItem, I see the Names in the TreeView. But if I click on a name, the given MouseEventHandler doesn´t get called.

Further I just want to request the text of the Element which trigger the MouseEvent, so that i can submit these name to a spezial funktion.

How can i realice such an MouseEvent? How is it possible to call it from the dynamicly created TreeItem?

Thank you for any help :)

cheerse Tobi


回答1:


TreeItems represent the data, not the UI component. So they don't generate mouse events. You need to register the mouse listener on the TreeCell. To do this, set a cell factory on the TreeView. The cell factory is a function that creates TreeCells as they are needed. Thus this will work for dynamically added tree items too.

You will need something like this:

TreeView<String> treeView ;

// ...

treeView.setCellFactory( tv -> {
    TreeCell<String> cell = new TreeCell<>();
    cell.textProperty().bind(cell.itemProperty());
    cell.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
        if (! cell.isEmpty()) {
            String value = cell.getItem();
            TreeItem<String> treeItem = cell.getTreeItem(); // if needed
            // process ...
        }
    });
    return cell ;
}


来源:https://stackoverflow.com/questions/26301086/how-to-give-an-dynamicly-loaded-treeviewitem-an-eventhandler

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