0

这是我的JTree

javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode(".Net Framework");
javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Install");
javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V1");
treeNode2.add(treeNode3);

treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V2");
treeNode2.add(treeNode3);

treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V3");
treeNode2.add(treeNode3);

treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V4");
treeNode2.add(treeNode3);
treeNode1.add(treeNode2);

treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Repair");
treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V1");
treeNode2.add(treeNode3);

treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V2");
treeNode2.add(treeNode3);

treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V3");
treeNode2.add(treeNode3);

treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("V4");
treeNode2.add(treeNode3);
treeNode1.add(treeNode2);

treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Removal");
treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Remove All");
treeNode2.add(treeNode3);
treeNode1.add(treeNode2);

jTree2.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
jScrollPane5.setViewportView(jTree2);

这是几乎可以工作的代码

DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree2.getLastSelectedPathComponent();

if (node == null) {
      //Nothing is selected.     
    return;
}

if (node.isLeaf()) {
    System.out.println(node);
} 

我希望能够做出 if 语句来说明安装节点中是否有叶节点 V1,然后执行此操作。只是不确定如何处理if(node.equals(thisleaf)))thisleaf对象应该等于什么。

4

1 回答 1

0

声明一个字段

private DefaultMutableTreeNode v1Node;

将第三行更改为

this.v1Node = new DefaultMutableTreeNode("V1");

并使用

if (node.equals(this.v1Node))

旁注:您应该通过简单地使用而不是完全限定名称来导入javax.swing.tree.DefaultMutableTreeNode并使您的代码更具可读性。DefaultMutableTreeNode您还应该选择有意义的变量名,而不是 treeNode1、jTree2 等。这些糟糕的名称会使代码非常难以理解。

于 2012-11-01T23:20:23.163 回答