1

我有一个带有自定义 TreeCellRenderer 的 JTree。

      DefaultMutableTreeNode myTreeRoot = new DefaultMutableTreeNode();
      JTree myTree = new JTree(myTreeRoot);
      myTree.setCellRenderer(new DefaultTreeCellRenderer() {

             @Override
             public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                     if (((DefaultMutableTreeNode) value).getUserObject() instanceof MyObject) {
                             System.out.println("============= my object ===========" + value);
                     }
                     return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
             }
      });

然后我在显示后将节点动态添加到树中。考虑只添加一个孩子的情况。

      MyObject object = new MyObject("Child Node");
      DefaultMutableTreeNode myTreeNode = new DefaultMutableTreeNode(object);
      myTreeRoot.add(myTreeNode);

然后我也隐藏树根

      myTree.expandRow(0);
      myTree.setRootVisible(false);
      myTree.setShowsRootHandles(true);
      if (myTreeRoot.getChildCount() != 0) {
            myTree.setSelectionRow(0);
      } 
      SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                   devicesTree.updateUI();
            }
      });

稍后还有另一个选项可以删除这些节点

      private void removeNode(MyObject object) {
            DefaultMutableTreeNode myTreeNode = getTreeeNode(object); //This method traverse through the tree and returns the corresponding node
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) myTree.getSelectionPath().getLastPathComponent();
            int selectedRow = -1;
            if (myTree.getSelectionRows().length > 0) {
                  selectedRow = myTree.getSelectionRows()[0];
            }
            boolean isSelected = selectedNode == myTreeNode;

            if (isSelected) {
                  if (myTree.getRowCount() == 1) {
                         myTree.clearSelection();
                  } else if (myTree.getRowCount() > selectedRow + 1) {
                         myTree.setSelectionRow(selectedRow + 1);
                  } else if (selectedRow != 0) {
                         myTree.setSelectionRow(0);
                  }
            }

            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) myTreeNode.getParent();
            parent.remove(myTreeNode);
            SwingUtilities.invokeLater(new Runnable() { 
                  public void run() {
                        myTree.updateUI();
                  }
            });
      }

现在我遇到的问题是当树的根部只有一个孩子并且如果我选择删除那个孩子,那么在删除之后 getTreeCellRendererComponent() 方法仍然指向那个被删除的对象。有什么线索吗?

4

0 回答 0