Solved

Adding a node to JTree

Posted on 2000-03-21
4
497 Views
Last Modified: 2008-02-26
I need some sample code for adding and removing nodes from a JTree, e.g. adding a child node of a child node, deleting a parent node. Does anyone have such code ?
0
Comment
Question by:jhandler
4 Comments
 
LVL 1

Expert Comment

by:dmaguillo
ID: 2639702
Here u have some Swing code examples:

http://www2.gol.com/users/tame/swing/examples/SwingExamples.html

In this page, u could find many code examples with Jtree.

Bye... :)
 
0
 
LVL 2

Expert Comment

by:stalefish
ID: 2640828
0
 
LVL 7

Expert Comment

by:conick
ID: 2641066
You basically need to change the model behind the GUI.
Say your model is based off of a DefaultMutableTreeNode:
You can use:
insert(MutableTreeNode node, int index);
remove(MutableTreeNode node);

After you change the model you have to update the View (JTree uses MVC (like the rest of Swing))
call revalidate() on the JTree.

stalefish and dmaquillo give good links for examples.
0
 
LVL 1

Accepted Solution

by:
yogeshr earned 150 total points
ID: 2652951
This is one example which I think should help you out . This is one of the standard examples given in one of the tutorials.

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeSelectionModel;
import java.net.URL;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;

public class TreeDemo extends JFrame {
    private JEditorPane htmlPane;
   private static boolean DEBUG = false;
    private URL helpURL;

private boolean playWithLineStyle=false;
 private String lineStyle = "Angled";

    public TreeDemo() {
        super("TreeDemo");

        DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
        createNodes(top);

   final JTree tree = new JTree(top);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);

tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                   tree.getLastSelectedPathComponent();

                if (node == null) return;

Object nodeInfo = node.getUserObject();
if (node.isLeaf()) {
    BookInfo book = (BookInfo)nodeInfo;
         displayURL(book.bookURL);
                    if (DEBUG) {
System.out.print(book.bookURL + ": \n");
                    }
                } else {
                  displayURL(helpURL);
                }
                if (DEBUG) {
System.out.println(nodeInfo.toString());
                }
            }
        });

        if (playWithLineStyle) {
            tree.putClientProperty("JTree.lineStyle", lineStyle);
        }

JScrollPane treeView = new JScrollPane(tree);

        htmlPane = new JEditorPane();
        htmlPane.setEditable(false);
        initHelp();
        JScrollPane htmlView = new JScrollPane(htmlPane);

        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(treeView);
        splitPane.setBottomComponent(htmlView);

        Dimension minimumSize = new Dimension(100, 50);
        htmlView.setMinimumSize(minimumSize);
        treeView.setMinimumSize(minimumSize);
        splitPane.setDividerLocation(100);                                        
        splitPane.setPreferredSize(new Dimension(500, 300));

        getContentPane().add(splitPane, BorderLayout.CENTER);
    }

    private class BookInfo {
        public String bookName;
        public URL bookURL;
        public String prefix = "file:"
                               + System.getProperty("user.dir")
                               + System.getProperty("file.separator");
        public BookInfo(String book, String filename) {
            bookName = book;
            try {
  bookURL = new URL(prefix + filename);
            } catch (java.net.MalformedURLException exc) {
                System.err.println("Attempted to create a BookInfo "
                                   + "with a bad URL: " + bookURL);
                bookURL = null;
            }
        }

        public String toString() {
            return bookName;
        }
    }

    private void initHelp() {
        String s = null;
        try {
            s = "file:"
                + System.getProperty("user.dir")
                + System.getProperty("file.separator")
                + "TreeDemoHelp.html";
            if (DEBUG) {
                System.out.println("Help URL is " + s);
            }
            helpURL = new URL(s);
            displayURL(helpURL);
        } catch (Exception e) {
            System.err.println("Couldn't create help URL: " + s);
        }
    }

    private void displayURL(URL url) {
        try {
            htmlPane.setPage(url);
        } catch (IOException e) {
            System.err.println("Attempted to read a bad URL: " + url);
        }
    }

    private void createNodes(DefaultMutableTreeNode top) {
        DefaultMutableTreeNode category = null;
        DefaultMutableTreeNode book = null;

        category = new DefaultMutableTreeNode("Books for Java Programmers");
        top.add(category);

        //original Tutorial
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Tutorial: Object-Oriented Programming for the Internet",
            "tutorial.html"));
        category.add(book);

        //Tutorial Continued
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Tutorial Continued: The Rest of the JDK",
            "tutorialcont.html"));
        category.add(book);

        //JFC Swing Tutorial
        book = new DefaultMutableTreeNode(new BookInfo
            ("The JFC Swing Tutorial: A Guide to Constructing GUIs",
            "swingtutorial.html"));
        category.add(book);

        //Arnold/Gosling
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Programming Language", "arnold.html"));
        category.add(book);

        //FAQ
        book = new DefaultMutableTreeNode(new BookInfo(
            "The Java FAQ", "faq.html"));
        category.add(book);

        //Chan/Lee
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Class Libraries: An Annotated Reference",
             "chanlee.html"));
        category.add(book);

        //Threads
        book = new DefaultMutableTreeNode(new BookInfo
            ("Concurrent Programming in Java: Design Principles and Patterns",
             "thread.html"));
        category.add(book);

        category = new DefaultMutableTreeNode("Books for Java Implementers");
        top.add(category);

        //VM
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Virtual Machine Specification",
             "vm.html"));
        category.add(book);

        //Language Spec
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Language Specification",
             "jls.html"));
        category.add(book);
    }

    public static void main(String[] args) {
        JFrame frame = new TreeDemo();
 
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });  
 
        frame.pack();
        frame.setVisible(true);
    }
}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Maven Project: Hibernate Dependencies Conflict 10 53
runtime exception 2 50
web project error add remove 1 55
Setup GlassFish 4 36
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question