Traversing JTree using DepthFirstEnumeration

Hi Java gurus,
I am working on a problem related to traversing a JTree. It is currently doing a BreadthFirstEnumeration ( as i understand) due to which i guess it is searching for the "search string" at all nodes of the 1st level of hierarchy then goes to second level and search all nodes then goes to third level of hierarchy etc.
i want to make it work in the "DepthFirstEnumeration " fashion where it comes to first node of 1st level, check all its children to match the "search string", then go to first child check all its children etc.... the come out and go to second node of the first level and repeate the traversing through its children process again just lik ethe first node.....
the cod ei have written for BreadthFirstEnumeration is as follows:
public void find(String searchString, boolean OptionGroupsOnly){
     try{
          if (searchString == null){
               searchString = "";
          searchString = searchString.toUpperCase();
          if (!this.searchString.equals(searchString) || breadthFirst == null){
               this.breadthFirst = root.breadthFirstEnumeration();
               this.searchString = searchString;
               this.treePaths = new ArrayList();
          while (breadthFirst.hasMoreElements()){
          OGTreeNode searchNode = (OGTreeNode)breadthFirst.nextElement();
               Object userObject = searchNode.getUserObject();
               if (userObject != null && searchNode.toString().toUpperCase().lastIndexOf(searchString)!= -1 && (!OptionGroupsOnly || userObject instanceof OptionGroupBean)){
                    if (statusPanel != null){
                         statusPanel.setMessage("Option/Group Found");
                    TreePath tp = new TreePath(searchNode.getPath());
                    this.setExpandsSelectedPaths(true);          
                    this.scrollPathToVisible(tp);
                    this.treePaths.add(tp);
                    TreePath[] treePathsArrray = new TreePath[1];
                    treePathsArrray = (TreePath[])treePaths.toArray(treePathsArrray);
                    this.setSelectionPaths( (TreePath[])treePaths.toArray(treePathsArrray));
                    return;
          breadthFirst=null;
          if (statusPanel != null){
               statusPanel.setMessage("Find Complete");
               JOptionPane.showMessageDialog(null, "Find Complete." );
          }catch(Exception e){
               Logger.getLogger(APPLOGGER).log(Level.WARNING, e.toString(), e);
can you suggest any change in the code???

Did you look at the [url http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html#method_summary]API for DefaultMutableTreeNode and see if there were any other methods that returned an enumeration?

Similar Messages

  • Problem inserting new node into JTree with depthFirstEnumeration()

    Hello,
    I'm currently trying to use depthFirstEnumeration() to add and delete nodes for a simple JTree. I've written a method to handle this, but it keeps coming back with an exception saying that 'new child is an ancestor'.
    All I'm trying to do is add and delete nodes from a JTree using add and remove buttons within a swing program. When a user adds the new node the JTree needs to be updated with new labels in sequential order dependent upon a depthFirst traversal of the JTree.
    My current code for the add button is as follows,
    public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            Enumeration e = rootNode.depthFirstEnumeration();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    while (e.hasMoreElements()) {
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)e.nextElement();
                     // treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    //System.out.print(newNode.getUserObject() + "" + newNodeSuffix++);
                    String label = "Node"+i;
                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    i++;
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);
                    //System.out.println();
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        } As you can see in the above code, I've tested the incrementing of the new nodes in a System.out.print() statement and they appear to be incrementing correctly. I just can't see how to correctly output the labels for the nodes.
    Any help and advice always appreciated.

    This is about the 5th posting on the same question. Here is the link to the last posting so you can see what has already been suggested so you don't waste your time making the same suggestion.
    http://forum.java.sun.com/thread.jspa?threadID=704980
    The OP doesn't seem to understand that nodes don't just rename themselves and that renderers will only display the text of the current node. If you want the text displayed to changed, then you need to change the text associated with each node, which means iterating through the entire tree to update each node with new text. Then again, maybe I don't understand the question, but the OP keeps posting the same question without any additional information.

  • How can i refresh a jtree using DefaultMutableTreeNode?

    I already create a jtree using DefaultMutableTreeNode, and i also could implement to it the addMouseListener to do a action when the user press every node......Also i used the following instruction to remove all nodes: root_tree.removeAllChildren(); and it instruction remove all the nodes....but when i :
    fill the tree
    compile my program
    i see the tree in my jpanel....it is Ok!
    now.....
    fill the tree
    remove the tree
    compile my program
    i see only the root (this i wish) it is Ok!
    But now i would like that after that i press a combo element (in the actionperformed method):
    remove the tree
    fill the three with the new nodes
    show the tree
    But my tree always is the same :(......is like it to need a repaint ....but i already implement it...but i obtain the same result.....
    Do somebody have any suggestion...or idea how i can do a refresh in my jtree?....
    Anybody could help me please?
    Thanks in advance.....
    Mary

    Construct your tree like this:DefaultMutableTreeNode rootNode = xxx;
    DefaultTreeModel model = new DefaultTreeModel( rootNode );
    JTree tree = new JTree( model );When you update the root node, just tell the model to fire the appropriate change event by doing this:model.reload( rootNode );or this:model.nodeStructureChanged( rootNode );or this:model.setRoot( rootNode )

  • Creating a dynamic jtree using datas retrieved by dom in xml parsing

    help me with code to create a dynamic jtree using data retrieved as nodes by xml parsing using dom

    Ok, so you want to make a tree. To determine the data that appears in a tree, you have to make a custom tree model. The API for this is at :
    http://java.sun.com/j2se/1.4.2/docs/api/
    A tutorial for using trees is at :
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    I assume you are going to be using Nodes, since you are using XML. For this I might start with something like
    class NodeTreeModel implements TreeModelI would then implement the 'getChildCount()' as the number of subnodes a node has, and the value of a tree node to the nodes value.
    Hope that starts you off.

  • Help with building a JTree using tree node and node renderers

    Hi,
    I am having a few problems with JTree's. basically I want to build JTree from a web spider. The webspide searches a website checking links and stores the current url that is being processed as a string in the variable msg. I wan to use this variable to build a JTree in a new class and then add it to my GUI. I have created a tree node class and a renderer node class, these classes are built fine. can someone point me in the direction for actually using these to build my tree in a seperate class and then displaying it in a GUI class?
    *nodeRenderer.java
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.net.*;
    public class nodeRenderer extends DefaultTreeCellRenderer
                                       implements TreeCellRenderer
    public static Icon icon= null;
    public nodeRenderer() {
    icon = new ImageIcon(getClass().getResource("icon.gif"));
    public Component getTreeCellRendererComponent(
    JTree tree,
    Object value,
    boolean sel,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus) {
    super.getTreeCellRendererComponent(
    tree, value, sel,
    expanded, leaf, row,
    hasFocus);
    treeNode node = (treeNode)(((DefaultMutableTreeNode)value).getUserObject());
    if(icon != null) // set a custom icon
    setOpenIcon(icon);
    setClosedIcon(icon);
    setLeafIcon(icon);
         return this;
    *treeNode.java
    *this is the class to represent a node
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.*;
    import java.net.*;
    * Class used to hold information about a web site that has
    * been searched by the spider class
    public class treeNode
    *Url from the WebSpiderController Class
    *that is currently being processed
    public String msg;
    treeNode(String urlText)
         msg = urlText;
    String getUrlText()
         return msg;
    //gui.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class gui extends JFrame implements Runnable
         *declare variable, boolean
         *thread, a object and a center
         *pane
         protected URL urlInput;
         protected Thread bgThread;
         protected boolean run = false;
         protected WebSpider webSpider;
         public gui()
              *create the gui here
              setTitle("Testing Tool");
         setSize(600,600);
         //add Buttons to the tool bar
         start.setText("Start");
         start.setActionCommand("Start");
         toolBar.add(start);
         ButtonListener startListener = new ButtonListener();
              start.addActionListener(startListener);
              cancel.setText("Cancel");
         cancel.setActionCommand("Cancel");
         toolBar.add(cancel);
         ButtonListener cancelListener = new ButtonListener();
              cancel.addActionListener(cancelListener);
              close.setText("Close");
         close.setActionCommand("Close");
         toolBar.add(close);
         ButtonListener closeListener = new ButtonListener();
              close.addActionListener(closeListener);
              //creat a simple form
              urlLabel.setText("Enter URL:");
              urlLabel.setBounds(100,36,288,24);
              formTab.add(urlLabel);
              url.setBounds(170,36,288,24);
              formTab.add(url);
              current.setText("Currently Processing: ");
              current.setBounds(100,80,288,24);
              formTab.add(current);
         //add scroll bars to the error messages screen and website structure
         errorPane.setAutoscrolls(true);
         errorPane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         errorPane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         errorPane.setOpaque(true);
         errorTab.add(errorPane);
         errorPane.setBounds(0,0,580,490);
         errorText.setEditable(false);
         errorPane.getViewport().add(errorText);
         errorText.setBounds(0,0,600,550);
         treePane.setAutoscrolls(true);
         treePane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         treePane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         treePane.setOpaque(true);
         treeTab.add(treePane);
         treePane.setBounds(0,0,580,490);
         treeText.setEditable(false);
         treePane.getViewport().add(treeText);
         treeText.setBounds(0,0,600,550);
         //create the tabbed window           
    centerPane.setBorder(new javax.swing.border.EtchedBorder());
    formTab.setLayout(null);
    errorTab.setLayout(null);
    treeTab.setLayout(null);
    centerPane.addTab("Search Parameters", formTab);
    centerPane.addTab("Error Messages", errorTab);
    centerPane.addTab("Website Structure", treeTab);
              //add the tool bar and tabbed pane
              getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
    getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);                    
              *create the tool bar pane, a center pane, add the buttons,
              *labels, tabs, a text field for user input here
              javax.swing.JPanel toolBar = new javax.swing.JPanel();
              javax.swing.JButton start = new javax.swing.JButton();
              javax.swing.JButton cancel = new javax.swing.JButton();
              javax.swing.JButton close = new javax.swing.JButton();      
              javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
              javax.swing.JPanel formTab = new javax.swing.JPanel();
              javax.swing.JLabel urlLabel = new javax.swing.JLabel();
              javax.swing.JLabel current = new javax.swing.JLabel();
              javax.swing.JTextField url = new javax.swing.JTextField();
              javax.swing.JPanel errorTab = new javax.swing.JPanel();
              javax.swing.JTextArea errorText = new javax.swing.JTextArea();
              javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
              javax.swing.JPanel treeTab = new javax.swing.JPanel();
              javax.swing.JTextArea treeText = new javax.swing.JTextArea();
              javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
              javax.swing.JTree searchTree = new javax.swing.JTree();
              *show the gui
              public static void main(String args[])
              (new gui()).setVisible(true);
         *listen for the button presses and set the
         *boolean flag depending on which button is pressed
         class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   Object object = event.getSource();
                   if (object == start)
                        run = true;
                        startActionPerformed(event);
                   if (object == cancel)
                        run = false;
                        startActionPerformed(event);
                   if (object == close)
                        System.exit(0);
         *this method is called when the start or
         *cancel button is pressed.
         void startActionPerformed (ActionEvent event)
              if (run == true && bgThread == null)
                   bgThread = new Thread(this);
                   bgThread.start();
              if (run == false && bgThread != null)
                   webSpider.cancel();
         *this mehtod will start the background thred.
         *the background thread is required so that the
         *GUI is still displayed
         public void run()
              try
                   webSpider = new WebSpider(this);
                   webSpider.clear();
                   urlInput = new URL(url.getText());
                   webSpider.addURL(urlInput);
                   webSpider.run();
                   bgThread=null;
              catch (MalformedURLException e)
                   addressError addErr = new addressError();
                   addErr.addMsg = "URL ERROR - PLEASE CHECK";
                   SwingUtilities.invokeLater(addErr);
              *this method is called by the web spider
              *once a url is found. Validation of navigation
              *happens here.
              public boolean urlFound(URL urlInput,URL url)
                   CurrentlyProcessing pro = new CurrentlyProcessing();
              pro.msg = url.toString();
              SwingUtilities.invokeLater(pro);
              if (!testLink(url))
                        navigationError navErr = new navigationError();
                        navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
                        return false;
              if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
                   return false;
              else
                   return true;
              *this method is called internally to check
         *that a link works
              protected boolean testLink(URL url)
              try
                   URLConnection connection = url.openConnection();
                   connection.connect();
                   return true;
              catch (IOException e)
                   return false;
         *this method is called when an error is
         *found.
              public void URLError(URL url)
              *this method is called when an email
              *address is found
              public void emailFound(String email)
              /*this method will update any errors found inc
              *address errors and broken links
              class addressError implements Runnable
                   public String addMsg;
                   public void run()
                        errorText.append(addMsg);
                        current.setText("Currently Processing: "+ addMsg);
              class navigationError implements Runnable
                   public String navMsg;
                   public void run()
                        errorText.append(navMsg);
              *this method will update the currently
              *processing field on the GUI
              class CurrentlyProcessing implements Runnable
              public String msg;
              public void run()
                   current.setText("Currently Processing: " + msg );
    //webspider.java
    import java.util.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.tree.*;
    import javax.swing.*;
    *this class implements the spider.
    public class WebSpider extends HTMLEditorKit
         *make a collection of the URL's
         protected Collection urlErrors = new ArrayList(3);
         protected Collection urlsWaiting = new ArrayList(3);
         protected Collection urlsProcessed = new ArrayList(3);
         //report URL's to this class
         protected gui report;
         *this flag will indicate whether the process
         *is to be cancelled
         protected boolean cancel = false;
         *The constructor
         *report the urls to the wui class
         public WebSpider(gui report)
         this.report = report;
         *get the urls from the above declared
         *collections
         public Collection getUrlErrors()
         return urlErrors;
         public Collection getUrlsWaiting()
         return urlsWaiting;
         public Collection getUrlsProcessed()
         return urlsProcessed;
         * Clear all of the collections.
         public void clear()
         getUrlErrors().clear();
         getUrlsWaiting().clear();
         getUrlsProcessed().clear();
         *Set a flag that will cause the begin
         *method to return before it is done.
         public void cancel()
         cancel = true;
         *add the entered url for porcessing
         public void addURL(URL url)
         if (getUrlsWaiting().contains(url))
              return;
         if (getUrlErrors().contains(url))
              return;
         if (getUrlsProcessed().contains(url))
              return;
         /*WRITE TO LOG FILE*/
         log("Adding to workload: " + url );
         getUrlsWaiting().add(url);
         *process a url
         public void processURL(URL url)
         try
              /*WRITE TO LOGFILE*/
              log("Processing: " + url );
              // get the URL's contents
              URLConnection connection = url.openConnection();
              if ((connection.getContentType()!=null) &&
         !connection.getContentType().toLowerCase().startsWith("text/"))
              getUrlsWaiting().remove(url);
              getUrlsProcessed().add(url);
              log("Not processing because content type is: " +
         connection.getContentType() );
                   return;
         // read the URL
         InputStream is = connection.getInputStream();
         Reader r = new InputStreamReader(is);
         // parse the URL
         HTMLEditorKit.Parser parse = new HTMLParse().getParser();
         parse.parse(r,new Parser(url),true);
    catch (IOException e)
         getUrlsWaiting().remove(url);
         getUrlErrors().add(url);
         log("Error: " + url );
         report.URLError(url);
         return;
    // mark URL as complete
    getUrlsWaiting().remove(url);
    getUrlsProcessed().add(url);
    log("Complete: " + url );
    *start the spider
    public void run()
    cancel = false;
    while (!getUrlsWaiting().isEmpty() && !cancel)
         Object list[] = getUrlsWaiting().toArray();
         for (int i=0;(i<list.length)&&!cancel;i++)
         processURL((URL)list);
    * A HTML parser callback used by this class to detect links
    protected class Parser extends HTMLEditorKit.ParserCallback
    protected URL urlInput;
    public Parser(URL urlInput)
    this.urlInput = urlInput;
    public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos)
    String href = (String)a.getAttribute(HTML.Attribute.HREF);
    if((href==null) && (t==HTML.Tag.FRAME))
    href = (String)a.getAttribute(HTML.Attribute.SRC);
    if (href==null)
    return;
    int i = href.indexOf('#');
    if (i!=-1)
    href = href.substring(0,i);
    if (href.toLowerCase().startsWith("mailto:"))
    report.emailFound(href);
    return;
    handleLink(urlInput,href);
    public void handleStartTag(HTML.Tag t,MutableAttributeSet a,int pos)
    handleSimpleTag(t,a,pos); // handle the same way
    protected void handleLink(URL urlInput,String str)
    try
         URL url = new URL(urlInput,str);
    if (report.urlFound(urlInput,url))
    addURL(url);
    catch (MalformedURLException e)
    log("Found malformed URL: " + str);
    *log the information of the spider
    public void log(String entry)
    System.out.println( (new Date()) + ":" + entry );
    I have a seperate class for parseing the HTML. Any help would be greatly appreciated
    mrv

    Hi Sorry to be a pain again,
    I have re worked the gui class so it looks like this now:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class gui extends JFrame implements Runnable
         *declare variable, boolean
         *thread, a object and a center
         *pane
         protected URL urlInput;
         protected Thread bgThread;
         protected boolean run = false;
         protected WebSpider webSpider;
         public String msgInfo;
         public String brokenUrl;
         public String goodUrl;
         public String deadUrl;
         protected DefaultMutableTreeNode rootNode;
    protected DefaultTreeModel treeModel;
         public gui()
              *create the gui here
              setTitle("Testing Tool");
         setSize(600,600);
         //add Buttons to the tool bar
         start.setText("Start");
         start.setActionCommand("Start");
         toolBar.add(start);
         ButtonListener startListener = new ButtonListener();
              start.addActionListener(startListener);
              cancel.setText("Cancel");
         cancel.setActionCommand("Cancel");
         toolBar.add(cancel);
         ButtonListener cancelListener = new ButtonListener();
              cancel.addActionListener(cancelListener);
              close.setText("Close");
         close.setActionCommand("Close");
         toolBar.add(close);
         ButtonListener closeListener = new ButtonListener();
              close.addActionListener(closeListener);
              //creat a simple form
              urlLabel.setText("Enter URL:");
              urlLabel.setBounds(100,36,288,24);
              formTab.add(urlLabel);
              url.setBounds(170,36,288,24);
              formTab.add(url);
              current.setText("Currently Processing: ");
              current.setBounds(100,80,288,24);
              formTab.add(current);
         //add scroll bars to the error messages screen and website structure
         errorPane.setAutoscrolls(true);
         errorPane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         errorPane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         errorPane.setOpaque(true);
         errorTab.add(errorPane);
         errorPane.setBounds(0,0,580,490);
         errorText.setEditable(false);
         errorPane.getViewport().add(errorText);
         errorText.setBounds(0,0,600,550);
         treePane.setAutoscrolls(true);
         treePane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         treePane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         treePane.setOpaque(true);
         treeTab.add(treePane);
         treePane.setBounds(0,0,580,490);
         treeText.setEditable(false);
         treePane.getViewport().add(treeText);
         treeText.setBounds(0,0,600,550);
         //JTree
         // NEW CODE
         rootNode = new DefaultMutableTreeNode("Root Node");
         treeModel = new DefaultTreeModel(rootNode);
         treeModel.addTreeModelListener(new MyTreeModelListener());
         tree = new JTree(treeModel);
         tree.setEditable(true);
         tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setShowsRootHandles(true);
         treeText.add(tree);
         //create the tabbed window           
    centerPane.setBorder(new javax.swing.border.EtchedBorder());
    formTab.setLayout(null);
    errorTab.setLayout(null);
    treeTab.setLayout(null);
    centerPane.addTab("Search Parameters", formTab);
    centerPane.addTab("Error Messages", errorTab);
    centerPane.addTab("Website Structure", treeTab);
              //add the tool bar and tabbed pane
              getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
    getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);     
              *create the tool bar pane, a center pane, add the buttons,
              *labels, tabs, a text field for user input here
              javax.swing.JPanel toolBar = new javax.swing.JPanel();
              javax.swing.JButton start = new javax.swing.JButton();
              javax.swing.JButton cancel = new javax.swing.JButton();
              javax.swing.JButton close = new javax.swing.JButton();      
              javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
              javax.swing.JPanel formTab = new javax.swing.JPanel();
              javax.swing.JLabel urlLabel = new javax.swing.JLabel();
              javax.swing.JLabel current = new javax.swing.JLabel();
              javax.swing.JTextField url = new javax.swing.JTextField();
              javax.swing.JPanel errorTab = new javax.swing.JPanel();
              javax.swing.JTextArea errorText = new javax.swing.JTextArea();
              javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
              javax.swing.JPanel treeTab = new javax.swing.JPanel();
              javax.swing.JTextArea treeText = new javax.swing.JTextArea();
              javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
              javax.swing.JTree tree = new javax.swing.JTree();
              *show the gui
              public static void main(String args[])
              (new gui()).setVisible(true);
         *listen for the button presses and set the
         *boolean flag depending on which button is pressed
         class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   Object object = event.getSource();
                   if (object == start)
                        run = true;
                        startActionPerformed(event);
                   if (object == cancel)
                        run = false;
                        startActionPerformed(event);
                   if (object == close)
                        System.exit(0);
         *this method is called when the start or
         *cancel button is pressed.
         void startActionPerformed (ActionEvent event)
              if (run == true && bgThread == null)
                   bgThread = new Thread(this);
                   bgThread.start();
                   //new line of code
                   treeText.addObject(msgInfo);
              if (run == false && bgThread != null)
                   webSpider.cancel();
         *this mehtod will start the background thred.
         *the background thread is required so that the
         *GUI is still displayed
         public void run()
              try
                   webSpider = new WebSpider(this);
                   webSpider.clear();
                   urlInput = new URL(url.getText());
                   webSpider.addURL(urlInput);
                   webSpider.run();
                   bgThread = null;
              catch (MalformedURLException e)
                   addressError addErr = new addressError();
                   addErr.addMsg = "URL ERROR - PLEASE CHECK";
                   SwingUtilities.invokeLater(addErr);
              *this method is called by the web spider
              *once a url is found. Validation of navigation
              *happens here.
              public boolean urlFound(URL urlInput,URL url)
                   CurrentlyProcessing pro = new CurrentlyProcessing();
              pro.msg = url.toString();
              SwingUtilities.invokeLater(pro);
              if (!testLink(url))
                        navigationError navErr = new navigationError();
                        navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
                        brokenUrl = url.toString();
                        return false;
              if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
                   return false;
              else
                   return true;
              *this method is returned if there is no link
              *on a web page, e.g. there us a dead end
              public void urlNotFound(URL urlInput)
                        deadEnd dEnd = new deadEnd();
                        dEnd.dEMsg = "No links on "+urlInput+"\n";
                        deadUrl = urlInput.toString();               
              *this method is called internally to check
         *that a link works
              protected boolean testLink(URL url)
              try
                   URLConnection connection = url.openConnection();
                   connection.connect();
                   goodUrl = url.toString();
                   return true;
              catch (IOException e)
                   return false;
         *this method is called when an error is
         *found.
              public void urlError(URL url)
              *this method is called when an email
              *address is found
              public void emailFound(String email)
              /*this method will update any errors found inc
              *address errors and broken links
              class addressError implements Runnable
                   public String addMsg;
                   public void run()
                        current.setText("Currently Processing: "+ addMsg);
                        errorText.append(addMsg);
              class navigationError implements Runnable
                   public String navMsg;
                   public void run()
                        errorText.append(navMsg);
              class deadEnd implements Runnable
                   public String dEMsg;
                   public void run()
                        errorText.append(dEMsg);
              *this method will update the currently
              *processing field on the GUI
              public class CurrentlyProcessing implements Runnable
                   public String msg;
              //new line
              public String msgInfo = msg;
              public void run()
                   current.setText("Currently Processing: " + msg );
         * NEW CODE
         * NEED THIS CODE SOMEWHERE
         * treeText.addObject(msgInfo);
         public DefaultMutableTreeNode addObject(Object child)
         DefaultMutableTreeNode parentNode = null;
         TreePath parentPath = tree.getSelectionPath();
         if (parentPath == null)
         parentNode = rootNode;
         else
         parentNode = (DefaultMutableTreeNode)
    (parentPath.getLastPathComponent());
         return addObject(parentNode, child, true);
         public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
    Object child)
         return addObject(parent, child, false);
         public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
         Object child,boolean shouldBeVisible)
         DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
         if (parent == null)
         parent = rootNode;
         treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
         if (shouldBeVisible)
         tree.scrollPathToVisible(new TreePath(childNode.getPath()));
              return childNode;
         public class MyTreeModelListener implements TreeModelListener
              public void treeNodesChanged (TreeModelEvent e)
                   DefaultMutableTreeNode node;
                   node = (DefaultMutableTreeNode)
                   (e.getTreePath().getLastPathComponent());
                   try
                        int index = e.getChildIndices()[0];
                        node = (DefaultMutableTreeNode)
                        (node.getChildAt(index));
                   catch (NullPointerException exc)
              public void treeNodesInserted(TreeModelEvent e)
              public void treeStructureChanged(TreeModelEvent e)
              public void treeNodesRemoved(TreeModelEvent e)
    I beleive that this line of code is required:
    treeText.addObject(msgInfo);
    I have placed it where the action events start the spider, but i keep getting this error:
    cannot resolve symbol
    symbol : method addObject (java.lang.String)
    location: class javax.swing.JTextArea
    treeText.addObject(msgInfo);
    Also the jtree is not showing the window that I want it to and I am not too sure why. could you have a look to see why? i think it needs a fresh pair of eyes.
    Many thanks
    MrV

  • How to create a JTree using a tree of my own

    Hello,
    I have an object which has a tree structure.
    I want to create a jtree that will hold the data from this tree of my own. I also want to be able to customize how nodes are rendered and to add a context menu with options like ADD/Remove/Move....
    Can you point me to a good tutorial?
    Can you help me?
    Thank you very much for your asistance.

    carstos,
    See this article for a not-extremely-well-written, but still useful, intro to trees:
    http://java.sun.com/products/jfc/tsc/articles/jtree/index.html
    After that see the Swing Tutorial at http://java.sun.com for specific help on popup menus, etc.
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Updating JTree Using a Custom TreeModel

    Hello,
    I have created a custom TreeModel that implements the TreeModel interface. The underlying data objects are stored in an existing tree structure similiar to a file/directory filesystem. When I add a new "file" object to the data model, I want to see it in the tree immediately. To make a long question short: what are the necessary steps to communicate with the JTree? Any info or references would be much appreciated.
    Thank You

    Thank you for your reply.
    Are you adding nodes or just expanding the JTree?Adding nodes (I also want to delete nodes)
    I don't know how to do this by just implementing
    TreeModel. This is using DefaultTreeModel.Yeah, I really don't want to use DefaultTreeModel because I would have to wrap my data objects as TreeNodes. Since my data objects are already in a tree structure, implementing TreeModel is much cleaner.
    It looks like I have to implement fireTreeNodesInserted() in my TreeModel, but I guess what I need to understand is how to register the JTree as a listener to my custom TreeModel. JTree doesn't directly implement TreeModelListener. I read somewhere that JTree automatically registers itself with the TreeModel, but that is not what I am observing.
    So..., I am still in need of more info.

  • Traversing HTML using JavaScript

    Can some one tell me if this is possible and point me to a good link to read up about this.
    I have a jsp page called MasterDeDisplay.jsp. It takes an object in and dynamically builds the page I want to display based on what was sent back from the database or an xml file.
    The page that is build contains for example the following html.
    <tr>
         <!-- Display single data element -->
         <td id="1"><input type="text" size="3" MAXLENGTH="3"
              class="hotspot_fund_id dynarch-menu-ctxbutton-left" name="iefT381c500"
              value="" id="500">
         </td>
         <!-- Display single data element -->
         <td id="2"><input type="text" size="17" MAXLENGTH="17"
              name="iffT381c540" value="0.000000"
              onblur="percentAmountFunction(this);" id="540"></td>
         <!-- Display single data element -->
         <td id="3"><input type="text" size="17" MAXLENGTH="17"
              name="iffT381c541" value=""
              onblur="percentAmountFunction(this);" id="541"></td>
         <!-- Display single data element -->
         <td id="4"><input type="text" size="3" MAXLENGTH="3"
              class="hotspot_fund_id dynarch-menu-ctxbutton-left" name="iefT381c505"
              value="" id="505">
         </td>
         <!-- Display single data element -->
         <td id="5"><input type="text" size="17" MAXLENGTH="17"
              name="iffT381c545" value="0.000000"
              onblur="percentAmountFunction(this);" id="545"></td>
         <!-- Display single data element -->
         <td id="6"><input type="text" size="17" MAXLENGTH="17"
              name="iffT381c546" value=""
              onblur="percentAmountFunction(this);" id="546"></td>
    </tr>You will notice that each td has an id.... this page has about 20 rows and each row looks identical except for the names.
    I want the onblur function for <td id="2"> to disable the input field (if certain conditions are met) in <td id="3"> the same for 3to2 5to6 and 6to5... but I do not know how to go from the input field to the td that it resides in. I can modify the id so that it is a concatination of the row count and the td count for example as 1~1 through 1~6 or something... that way if I can get to the td I can parse it's id and decide the new id to get using getElementbyId function.
    And no I can not mess with the id of the input field... that was put there by another developer and is being used by other aspects of the application...

    looks like I was able to do this without traversing.. thanks if anyone takes a look at this.
    of course I haven't made it work yet... just proved that the data I need is available :)

  • Delete a node from JTree using removeSelectionPath question

    hi guys,
    how do i delete a node using removeSelectionPath?
    jtree.removeSelectionPath(treePath);
    it dont seem to work
    cheers

    Each of that type of learning interactions has a minimum and a maximum number of buttons (nodes). For the circle matrix I found a minimum of 5 (central + one ring). When you select one of the buttons you should see a minus sign that allows to delete a button.

  • Create JTree using data from DataBase

    Hi all,
    I have GUI with JTree, and i have data in database with ParentID, ChiledID fileds,
    i want to crate tree structure from using data in database.
    can you people tell me how can i proceed, I will get a data as List of Vectors from DB.
    Thanks
    Daya

    i got the solution,
    what i did i having object class extended DefaultMutableTreeNode and i have list of objects class refrence and i know which is parent and a child so just add the child refrence to parent refrence which stored in list.
    Thanks
    daya

  • Partial Selection in Jtree using checkbox for every node

    I have a application which uses a JTree. For each node in the tree, there is a checkbox attached to the node using a customized TreeCellRenderer. When some items of a node are selected i.e not all children of a node are selected using the chechboxes, how do i indicate using the checkbox of the parent node that only a partial list of nodes is selected. For this, i need to draw a little square in the checkbox indicating that it is partially selected. Any advice on this matter would be very helpful.

    It's a bit complicated. The default cell renderer doesn't actually put the tree nodes on your screen, it just paints the looks of them. That is, you see them on screen, but they are just painted, all mouse clicks etc. are sent directly to the JTree.
    In order to have a button in a tree node, and have that button respond to clicks, I believe you'd have to put the button in a TreeCellEditor. This means users will have to triple click the node to get the Editor in the renderer's place (db click only expands/implodes nodes).
    I have sucessfully used http://propertytree.dev.java.net/ to customize the behaviour of tree nodes, but I never have put a button in there... Have a look, you'll see what methods you need to overwrite.

  • Problems with JTree using removeSelectedPath

    Hi. In my application, I would like the user to be able to select anything in the JTree with the following exceptions:
    - a selected node cannot be an ancestor of another node
    - a selected node must be of the same node type
    Let's say I have five different node types (a,b,c,d,e) that correspond to each level of the tree.
    root
    |-node 1 (node type a)
    | |-node 2 (node type b)
    | | |- node 3 (node type c)
    | |- node 4 (node type b)
    |-node 5 (node type a)
    A user would be able to select nodes 2 and 4 since they are the same type and node 4 isn't an ancestor of node 2. So, if the user clicked on node 2, held the shift key and clicked on node 4, I'd like to automatically unselect node 3.
    I tried to do this by adding a TreeSelectionListener, but each call to removeSelectionPath calls itself again since the tree is being "selected".
    Does anyone have an elegant way? I was thinking about removing the listener when the valueChanged() method was called and then add it back when I'm done modifying the tree...
    TIA,
    Chester

    The not-so-elegant way is to use the TreeSelectionListener (I don't see how you can avoid using that) and to incorporate a boolean flag in your program that is set to true when your program is changing the selection (via removeSelectionPath) and to false otherwise. Then your listener can check the flag to see who's making the change. Not so elegant, but not as inelegant as removing the listener and then adding it back.

  • Reorder items in JTree using drag-and-drop

    Title says it all: before I start re-inventing the wheel, any code out there?
    Think of the code that I need as an outliner.

    Did you ever find a solution to this. I'm looking to implement a similar interface using a JList where the user can reorder drawing layers by dragging and dropping.
    I'm temped to use a scrollpane and roll my own drag reorder code, so any supported behaviors would be welcome.
    thanks,
    Steven

  • Expand JTree using

    hi there,
    I have a JTree with DefaultMutableTreeNode as nodes each node represent a string.
    I have to ways to watch my data JTable and and JTree both are visible, I need to sync between them.
    sync the JTable to the JTree was easy, but now I don't have a clue how to sync the JTree to the JTable.
    both contain string as data.
    cause my app is kind of a Virtual HD, I display on the JTree and the JTable my files and directories.
    my intuition was to pass the current path to the JTree but I don't know how to create a TreePath to the needed node
    thank you

    Convert your node path to a TreePath and call expandPath.

  • Creating Jtree Using ArryList

    Good Evening.
    Am new to swing, i need to create Dynamic Swing JTree for below StringArray.
    Root has leaf node and Folders
    Folders may have Folder node or leaf node
    String path[] = {"Root/TS1",
         "Root/Folder1/TS2",
         "Root/Foder2/Folder3/TS3"};
    It would be great help if you send me the code.
    Thanks in advance.
    Shrinivas
    Edited by: Shrinivas on Feb 18, 2011 7:00 AM

    Hi Shrinivas,
    one way could be to create the nodes level by level: first all level 0 nodes, than all level 1 nodes, and so on. In this case we don't have to bother about a parent node being already created or not. To find the parent node for a particular node we just make a simple method that processes the tree recursively, for example like this:
    private void buildTree(final String[] flatData, final int maxLevel) {
        for (int level = 0; level < maxLevel; level++) {
            for (String nodeData : flatData) {
                String[] nodePath = nodeData.split("/");
                if (level < nodePath.length) {
                    DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(nodePath[level]);
                    parent = (DefaultMutableTreeNode) tree.getModel().getRoot();
                    findParent(tree.getModel().getRoot(), nodePath, level);
                    if (parent != null) {//null = exists already
                        ((DefaultTreeModel) tree.getModel()).insertNodeInto(newChild, parent, parent.getChildCount());
    private void findParent(final Object o, final String[] nodePath, final int level) {
        int cc = tree.getModel().getChildCount(o);
        for (int i = 0; i < cc; i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) tree.getModel().getChild(o, i);
            if (child.getLevel() == level && child.toString().equals(nodePath[level - 1])) {
                parent = child;
            } else if (child.getLevel() == (level + 1) && child.toString().equals(nodePath[level])) {
                parent = null;//exists already
            if (!tree.getModel().isLeaf(child)) {
                tree.expandPath(new TreePath(child.getPath()));
                findParent(child, nodePath, level);
    }Cheers,
    André

Maybe you are looking for

  • Downloaded a 20 dollar app and it wont let me put on phone... PLEASE READ!

    I got the iphone today and i downloaded Beat Maker which ive seen a lot of positive reviews. So i got my phone and i had a plane to catch at 5. So i went home and synced my phone and got the music on there assuming if i needed to add videos, etc.. i

  • Problem between itunes and windows 8.

    I installed iTunes 11 on Windows 8, but i noticed a serious problem. On the surface it seems to work fine, but when i turn off iTunes processes SERVER SYNC and DISTONOTED  continue to work tirelessly, putting enormous effort the CPU forced to work 10

  • Journal Entry Template

    Dear Experts:       I am using BPC 7.0 NW and just seeting the journal entry template. However, the journal template only show detail information, and the header dimensions are hidden. I only can adjust this from Excel's Menu. After that, when I open

  • .ds store file

    I've noticed recently that I've got a file on my desktop named ".ds store", and it's a file that I cannot throw away because it keeps replicating itself whenever I move it to the trash. I've also noticed that there is also a ".ds store" file in every

  • SAP Netweaver 7.01 Abap Trial Version - Flight Model

    Hello everyone, Iu2019ve installed SAP Netweaver 7.01 Abap Trial Version for practicing purpose. Iu2019ve the handbooks of the course version 63 (Year 2008). It uses the structure type BC400_S_FLIGHT and the class CL_BC400_FLIGHTMODEL among others bu