Solved

Adding a node to JTree

Posted on 2000-03-21
4
495 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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

777 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