Delete tree node : JTree Node « Swing « Java Tutorial






import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class DeleteNodes extends JFrame {

  protected JTree tree;

  public static void main(String[] args) {
    DeleteNodes dn = new DeleteNodes(new JTree());
    dn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    dn.setSize(400, 300);
    dn.setVisible(true);
  }

  public DeleteNodes(JTree jt) {
    super();
    tree = jt;
    getContentPane().add(tree);
    tree.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent event) {
        if (((event.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
            && (tree.getSelectionCount() > 0)) {
          showMenu(event.getX(), event.getY());
        }
      }
    });
  }

  protected void showMenu(int x, int y) {
    JPopupMenu popup = new JPopupMenu();
    JMenuItem mi = new JMenuItem("Delete");
    TreePath path = tree.getSelectionPath();
    Object node = path.getLastPathComponent();
    if (node == tree.getModel().getRoot()) {
      mi.setEnabled(false);
    }
    popup.add(mi);
    mi.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        deleteSelectedItems();
      }
    });
    popup.show(tree, x, y);
  }

  protected void deleteSelectedItems() {
    DefaultMutableTreeNode node;
    DefaultTreeModel model = (DefaultTreeModel) (tree.getModel());
    TreePath[] paths = tree.getSelectionPaths();
    for (int i = 0; i < paths.length; i++) {
      node = (DefaultMutableTreeNode) (paths[i].getLastPathComponent());
      model.removeNodeFromParent(node);
    }
  }
}








14.67.JTree Node
14.67.1.Get child count, depth, leaf count
14.67.2.Adding a Node to a JTree Component
14.67.3.Delete tree node
14.67.4.Removing a Node to a JTree Component
14.67.5.Expression TreeExpression Tree
14.67.6.Swing TreeSwing Tree
14.67.7.JTree node mouse click event
14.67.8.A JTree subclass that displays the tree of AWT or Swing component that make up a GUI
14.67.9.Tree with custom icon
14.67.10.CheckBox Tree node
14.67.11.Get path for all expanded or not expanded tree pathes
14.67.12.Converting All Nodes in a JTree Component to a TreePath Array
14.67.13.Expanding or Collapsing All Nodes in a JTree Component
14.67.14.JTree root cannot be removed with removeNodeFromParent(), use DefaultTreeModel.setRoot() to remove the root
14.67.15.Searching node in a JTree