0

I'm trying to remove an Element for my undo function but I want to just remove the last thing added to the JTree.

For removal, I'm just modifying my method for Cut:

private void performUndoAction() {        

        if (tree != null) {

            TreePath path = tree.getSelectionPath();
            if (path != null) {

                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                if (node != tree.getModel().getRoot()) {

                    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                    if (node.getUserObject() instanceof Attribute) {

                        Attribute at = (Attribute) node.getUserObject();
                        at.getParent().removeAttribute(at);
                        cut = at;
                    }
                    else if (node.getUserObject() instanceof Element) {

                        Element el = (Element) node.getUserObject();
                        el.getParent().removeContent(el);
                        cut = el;
                    } else if (node.getUserObject() instanceof Text) {

                        cut = ((Text) node.getUserObject()).getText();
                        Element el = (Element) parent.getUserObject();
                        el.setText("");
                    }
                    parent.remove(node);
                    tree.updateUI();
                }
            }
        } 
    }       
Chea Indian
  • 677
  • 3
  • 9
  • 16
  • 1
    1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) This seems to be 'How do I get a reference to a non-selected node?'. Is that right? – Andrew Thompson Jul 18 '12 at 01:34

1 Answers1

0

A quick and dirty way would be to make a second tree and add all of the nodes to it before removing one from the main tree, and to undo just replace the main tree with the copy from before. Not the prettiest solution, but it may get you beyond that point.

I have actually done this with an arraylist and just build the tree from the arraylist content.

Logan
  • 2,369
  • 19
  • 20