How do I remove a node from JTree?

The code below demonstrates how to delete a node from a JTree component.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JTreeRemoveNode extends JFrame {
    public JTreeRemoveNode() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JTreeRemoveNode().setVisible(true));
    }

    private void initializeUI() {
        setSize(400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Address Book");
        String[] names = new String[]{"Alice", "Bob", "Carol", "Mallory"};
        for (String name : names) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
            root.add(node);
        }

        final JTree tree = new JTree(root);
        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(400, 400));

        JButton removeButton = new JButton("Remove");
        removeButton.addActionListener(e -> {
            DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

            TreePath[] paths = tree.getSelectionPaths();
            if (paths != null) {
                for (TreePath path : paths) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                            path.getLastPathComponent();
                    if (node.getParent() != null) {
                        model.removeNodeFromParent(node);
                    }
                }
            }
        });

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(tree, BorderLayout.CENTER);
        getContentPane().add(removeButton, BorderLayout.SOUTH);
    }
}

Remove a node from JTree

How do I get the selected nodes of a JTree?

The following example show how to use the JTree.getSelectionPaths() method to get the selected node of a JTree component. This method returns an array of TreePath objects. In the case to get the last node in the path we can call the TreePath.getLastPathComponent().

In the code below when you pressed the button the listener gets the selection paths and print out the last path component of the selected nodes.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;

public class JTreeGetSelectedNode extends JFrame {
    public JTreeGetSelectedNode() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JTreeGetSelectedNode().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Countries");
        DefaultMutableTreeNode asia = new DefaultMutableTreeNode("Asia");
        String[] countries = new String[]{"India", "Singapore", "Indonesia", "Vietnam"};
        for (String country : countries) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
            asia.add(node);
        }

        DefaultMutableTreeNode northAmerica = new DefaultMutableTreeNode("North America");
        countries = new String[]{"United States", "Canada"};
        for (String country : countries) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
            northAmerica.add(node);
        }

        DefaultMutableTreeNode southAmerica = new DefaultMutableTreeNode("South America");
        countries = new String[]{"Brazil", "Argetina", "Uruguay"};
        for (String country : countries) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
            southAmerica.add(node);
        }

        DefaultMutableTreeNode europe = new DefaultMutableTreeNode("Europe");
        countries = new String[]{"United Kingdom", "Germany", "Spain", "France", "Italy"};
        for (String country : countries) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
            europe.add(node);
        }

        root.add(asia);
        root.add(northAmerica);
        root.add(southAmerica);
        root.add(europe);

        final JTree tree = new JTree(root);
        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(500, 500));

        JButton button = new JButton("Get Selected");
        button.addActionListener(e -> {
            TreePath[] paths = tree.getSelectionPaths();
            for (TreePath path : paths != null ? paths : new TreePath[0]) {
                System.out.println("You've selected: " + path.getLastPathComponent());
            }
        });

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}

How do I use a JTree component?

The example introduce you how to use the JTree swing component to create a presentation of hierarchical data. The hierarchical data can be viewed in expand mode or collapse mode.

To create an item of the tree we create an instance of DefaultMutableTreeNode which located in the javax.swing.tree package. This class implements the TreeNode and MutableTreeNode interfaces. Mutable means that the node can be changed. It can be added new children node or deleted children node from their parent node.

Below we create a tree component to display information about week day names and the month names. The Root node have the Days and Months. The Days node contains a week day names and the Months node contains the month names.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.text.DateFormatSymbols;

public class JTreeDemo extends JFrame {
    public JTreeDemo() {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JTreeDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Creating tree node of day names.
        DefaultMutableTreeNode day = new DefaultMutableTreeNode("Days");
        DefaultMutableTreeNode sun = new DefaultMutableTreeNode("Sunday");
        DefaultMutableTreeNode mon = new DefaultMutableTreeNode("Monday");
        DefaultMutableTreeNode tue = new DefaultMutableTreeNode("Tuesday");
        DefaultMutableTreeNode wed = new DefaultMutableTreeNode("Wednesday");
        DefaultMutableTreeNode thu = new DefaultMutableTreeNode("Thursday");
        DefaultMutableTreeNode fri = new DefaultMutableTreeNode("Friday");
        DefaultMutableTreeNode sat = new DefaultMutableTreeNode("Saturday");

        // Adding the day nodes into day tree node.
        day.add(sun);
        day.add(mon);
        day.add(tue);
        day.add(wed);
        day.add(thu);
        day.add(fri);
        day.add(sat);

        // Creates tree node of month names using a for loop where the
        // month names is obtained using the DateFormatSymbols class.
        DefaultMutableTreeNode month = new DefaultMutableTreeNode("Months");
        String[] months = DateFormatSymbols.getInstance().getMonths();
        for (String monthName : months) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(monthName);
            month.add(node);
        }

        // Creating a root node for our JTree and add day and month items
        // to the tree.
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        root.add(day);
        root.add(month);

        // Creating an instance of JTree using the instance of
        // DefaultMutableTreeNode. We also create a scroll pane for our
        // tree container.
        JTree tree = new JTree(root);
        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(250, 450));
        getContentPane().add(pane);
    }
}
Swing JTree Demo

Swing JTree Demo