我在javafx2中创建了树视图。我需要编写事件来获取点击的节点名称。
请告诉我怎么做?
答案 0 :(得分:40)
示例代码:
treeView.getSelectionModel().selectedItemProperty().addListener( new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue,
Object newValue) {
TreeItem<String> selectedItem = (TreeItem<String>) newValue;
System.out.println("Selected Text : " + selectedItem.getValue());
// do what ever you want
}
});
答案 1 :(得分:12)
略有更新版本
treeView.getSelectionModel().selectedItemProperty()
.addListener(new ChangeListener<TreeItem<String>>() {
@Override
public void changed(
ObservableValue<? extends TreeItem<String>> observable,
TreeItem<String> old_val, TreeItem<String> new_val) {
TreeItem<String> selectedItem = new_val;
System.out.println("Selected Text : " + selectedItem.getValue());
// do what ever you want
}
});
答案 2 :(得分:11)
略微更新版本,使用lambdas清理它:
treeView.getSelectionModel()
.selectedItemProperty()
.addListener((observable, oldValue, newValue) -> System.out.println("Selected Text : " + newValue.getValue()));