Solved

Adding a node to JTree

Posted on 2000-03-21
4
496 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: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

790 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