How to give an dynamicly loaded TreeViewItem an Ev

2019-06-08 18:53发布

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条回答
地球回转人心会变
2楼-- · 2019-06-08 19:17

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 ;
}
查看更多
登录 后发表回答