我想用上下文菜单创建这个简单的javaFX TreeView示例,它可以从树中删除节点:
public class TreeViewSample extends Application {
private final Node rootIcon = new ImageView(
new Image(getClass().getResourceAsStream("folder_16.png"))
);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Tree View Sample");
TreeItem<String> rootItem = new TreeItem<String> ("Inbox", rootIcon);
rootItem.setExpanded(true);
for (int i = 1; i < 6; i++) {
TreeItem<String> item = new TreeItem<String> ("Message" + i);
rootItem.getChildren().add(item);
}
TreeView<String> tree = new TreeView<String> (rootItem);
StackPane root = new StackPane();
root.getChildren().add(tree);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
我测试了此上下文菜单以删除右键单击所选节点:
final ContextMenu contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("About");
}
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
MenuItem item3 = new MenuItem("Remove");
item3.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
DynamicTreeNodeModel c = treeView.getSelectionModel().getSelectedItem().getValue();
boolean remove = treeView.getSelectionModel().getSelectedItem().getChildren().remove(c);
System.out.println("Remove");
}
});
contextMenu.getItems().addAll(item1, item2, item3);
treeView.setContextMenu(contextMenu);
由于某种原因,代码无效。你能帮我解决这个问题吗?
答案 0 :(得分:8)
您正尝试从其自己的子节点中删除所选节点。由于那里不存在,所以没有任何反应。您需要从父母的子女中删除所选节点。
MenuItem item3 = new MenuItem("Remove");
item3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
TreeItem c = (TreeItem)treeView.getSelectionModel().getSelectedItem();
boolean remove = c.getParent().getChildren().remove(c);
System.out.println("Remove");
}
});