Moving expanded tree nodes in a JTree

Hello.
I have built a JTree that represents my hard disks. The files are sorted alphabetically. I already have built methods to create and remove directories, using the removeNodeFromParent and insertNodeInto methods in DefaultTreeModel.
Now I would like to rename a directory, so (because of the sorting) sometimes nodes should move some indices up or down. When I use the methods mentioned above it just works okay, but when I have expanded the node to be renamed it and all of its children get collapsed.
My question is: does anyone know of a convenient method to use for this problem? Thanks in advance.
Kind regards, Levi.

Hello guys,
thanks for all your replies. I've figured it out myself (not with the tree API, though) using two recursive methods.
Kind regards,
Levi

Similar Messages

  • Expanding Tree nodes

    is it possible to expand tree node on rollover instead of
    clicking on the triangle?

    yes, that worked. thanks.
    private function itemRollOverHandler(event:ListEvent):void{
    tree.expandItem(event.itemRenderer.data, true, true);
    I think I was looking for something like getItem(index)..
    something similar to Flash AS 2 components.

  • Expand tree node by clicking onto the node label

    I have followed this example to expand the nodes with a clic on the tree :
    [http://www.oracle.com/technetwork/developer-tools/adf/learnmore/20-expand-tree-node-from-label-169156.pdf]
    My code:
    JSPX:
    <af:resource type="javascript" source="js/glasspane.js"/>
    <af:tree value="#{bindings.OpcionesPadreView1.treeModel}" var="node"
    rowSelection="single" id="t1" partialTriggers=":::cbNuevCpta"
    binding="#{pageFlowScope.GestionDocumentos.t1}"
    selectionListener="#{bindings.OpcionesPadreView1.treeModel.makeCurrent}">
    <f:facet name="nodeStamp">
    <af:commandImageLink text="#{node.Gesdopcach}" id="ot1"
    action="#{bindings.LoadDir.execute}"
    actionListener="#{bindings.LoadFile.execute}"
    icon="/images/GestionDocumentos/folder20x20.png"
    partialSubmit="true">
    </af:commandImageLink>
    </f:facet>
    <af:clientListener method="expandTree" type="selection"/>
    </af:tree>
    Js:
    function expandTree(evt) {
    alert('In');
    var tree = event.getSource();
    rwKeySet = event.getAddedSet();
    var firstRowKey;
    for (rowKey in rwKeySet) {
    firstRowKey = rowKey;
    if (tree.isPathExpanded(firstRowKey)) {
    tree.setDisclosedRowKey(firstRowKey, false);
    }else {
    tree.setDisclosedRowKey(firstRowKey, true);
    When i clic on the labels the tree doesn't expand, the alert also is not shown. The problem could be the <af:resource>, but i have this tag in all my pages and all javascripts work. I also changed the commandLink with an outputText, but doesn't work.
    Edited by: Miguel Angel on 21/06/2012 12:53 PM

    At least the call the javascript works, but this line doesn't work, anybody know why?:
    rwKeySet = evt.getAddedSet();

  • Expand tree nodes

    Hi Experts,
    Working jdev 11.1.1.3.0.
    we are using tree component on the page which as 6 childs. so if i click on add button once it will add child to that node and once i click on save done will come back to tree page. so everything is working fine. but the problem is once the node is added child node is not expanding. to resolve this issue i am using tree object in session, but while using this process its taking lot of performance.
    manually i can able to expand the tree but if once i add node to the parent tree and coming back to the page node is not expanding i have to manually expand it.
    so can any one suggest me what could be the best approch to expand the tree.
    Thanks,

    Hi,
    Hope followings useful
    http://andrejusb.blogspot.com/2010/02/how-to-traverse-adf-tree.html
    http://www.oracle.com/technetwork/developer-tools/adf/learnmore/20-expand-tree-node-from-label-169156.pdf
    http://www.oracle.com/technetwork/developer-tools/adf/learnmore/21-expand-tree-on-initial-render-169158.pdf

  • Cannot expand tree nodes using t:tree tag

    Hi, I have a question.
    I am a beginner of JSF. I am trying to deploy a very simple tree using <t:tree> in my local tomcat server, similar to the following one:
    http://www.irian.at/myfaces/tree.jsf
    The result is that the tree is properly displayed, but I cannot expand the nodes when I click on the "+" icon of the nodes.
    Can someone help me? Thanks a lot!

    Take a look at Lilya Jsf Widgets and Ajax Capabilities at http://qlogic.ma/lilya
    the new era of technology

  • Expand tree node upto a fix level

    Hi all,
    I have a hierarchical tree in forms. I can expand all the node by the following code
    DECLARE
    htree ITEM;
    node ftree.node;
    state varchar2(30);
    BEGIN
    -- Find the tree itself.
    htree := Find_Item('BLOCK17.T_POP'); -- Find the root node of the tree.
    node := Ftree.Find_Tree_Node(htree, '');
    -- Loop through all nodes and expand each one if it is collapsed.
    WHILE NOT Ftree.ID_NULL(node) LOOP
    state := Ftree.Get_Tree_Node_Property(htree, node, Ftree.NODE_STATE);
    IF state = Ftree.COLLAPSED_NODE THEN
    Ftree.Set_Tree_Node_Property(htree, node, Ftree.NODE_STATE, Ftree.EXPANDED_NODE); END IF;
    node := Ftree.Find_Tree_Node(htree, '', ftree.find_NEXT,Ftree.NODE_LABEL,'', node); END LOOP;
    END;
    But what i need is expand the tree upto a fix level. Suppose uptp level1 or level2. The rest of the level will be collapsed. What can i do? Pls help.
    Best regards
    Tarik

    Using node_depth you would change
    IF state = Ftree.COLLAPSED_NODE THENto
    IF state = Ftree.COLLAPSED_NODE and to_numbeR(ftree.get_tree_node_property(htree, node, node_depth)) <= 2 THENThis might not be the most efficient code because it will still loop through every node in the tree, but I think it will work.

  • Expanding Tree nodes in Web Dynpro

    Hi,
    I have created a recursive tree with two main nodes. These nodes contain subnodes.
    The filling of these nodes has been done in wdDoInit().
    The problem is that whenever I expand the second node, the first node also gets expanded.. even when it (first node) is not expanded.
    When I go to some other window and then come back to this window (wdModify()),it works properly. i.e. the first node does not get expanded.
    Plz help........
    Thanks in Advance.
    Regards,
    harshada.

    Hi Harshada
    It looks strange to me that you use two main nodes on the first level. In the most cases it's enough to have only one node for each level of a tree.
    Are the two nodes mapped to the same context node? If so you do not need the second node I think. Because when the first node is expanded the mapped context node will get the corresponding lead selection. But the lead selection will influence on the second node as well. That's why the tho nodes expand simultaneously.
    BR
    Sergei

  • How to get a Tree Node Value when a Tree is Expanded

    My reqiurement is when i Expand a Tree i need the Expanded tree Node Value. For Example Consider Parent as a Root Node of a Tree, and Consider its two Children Child1 and Child2.
    When + Parent Expanded
    I will Get the Output as --Parent
    - Child1
    - Child2
    so As when i expand the Tree i must Get the String Value Parent.

    duplicate
    How to get a Tree Node Value when a Tree is Expanded

  • Tree Nodes has White Outline/Border

    Hi,
    I'm using an ADF tree located inside a panelGroupLayout.
    The panelGroupLayout has the background color "light blue".
    At runtime each tree node is displayed with a surrounding white outline and that can only appear when you have a background color different than white (in my case the panelGroupLayout is "light blue").
    Does anybody knows how to remove that outline? or to change its color?
    Thanks,
    Alain.

    Here are the skin seletors
    tr:tree Component
    Icon Selectors
    Name      Description
    af|tree::expanded-icon      This icon is displayed before the expanded tree node.
    af|tree::collapsed-icon      This icon is displayed before the collapsed tree node.
    af|tree::no-children-icon      This icon is displayed instead of the expanded/collapsed icon, when the node has no children
    af|tree::line-icon      This icon is used as a vertical line between the nodes.
    af|tree::line-middle-icon      This icon is used as the horizontal line in the background of the expand/collapse icon of the node, in the case the node is not the last sibling of its parent node.
    af|tree::line-last-icon      This icon is used as the horizontal line in the background of the expand/collapse icon of the node, in the case the node is the last sibling of its parent node.
    af|tree::node-icon      This icon selector is used in the case the Node class has a getNodeType() method that returns the node type as string. The nodetype gets added to this selector, separated by a ':'. If the node is a container (has children) the following suffixes get added depending on the expanded/collapsed state: '-expanded' / '-collapsed'. e.g. "af|tree::node-icon:container-collapsed", "af|tree::node-icon:container-expanded", "af|tree::node-icon:noncontainer".
    Trinidad properties
    Name      Description
    -tr-show-lines      Valid values are true or false (default true). Determines whether the tree lines are displayed or not. e.g., af|tree {-tr-show-lines:false} will not show the lines of the tree.Timo

  • Programmatically selecting a Tree node

    Hi there,
    Given a TreePath object, I need to know how to programmatically select a tree node on a JTree.
    Here's the situation:
    I have a simple text editor project which has a JTree on its interface representing the local file system. The program has a SaveAs dialog box which also has a duplicate JTree as the one on the main interface (directories only). As the user selects the directory in which they wish to save the open file in the SaveAs dialog box, I need somehow to programmatically cause the JTree on the main interface to correspondingly select the same directory. How is this done?
    The whole point of this is so that I can then add a new leaf node to the tree at the specified directory location. I've tried simply setting the jTree1.setSelectionPath(...) method and even tried to call the valueChanged(...) method of the TreeSelectionListener object as you can see from the code snippet below, but none of these approaches have been successful.
    Please advise,
    Alan
    public void createLeafNode()
         jTree1.repaint();
         if(path == null)
            return;
         jTree1.setSelectionPath(path);
         //SelectionListener.valueChanged(new TreeSelectionEvent(jTree1, path, true, oldLeadPath, newLeadPath));
         //System.out.println("path is: " + path.toString());
         DefaultTreeNode parent = getTreeNode(path);
         //System.out.println("parent is " + parent.toString());
         //Create the child node
         IconData idata = new IconData(ICON_LEAF, new FileNode(new SpecialFile(ref.FileOpen)));
         DefaultTreeNode node = new DefaultTreeNode(idata);
         parent.add(node);
         //Tell the model that the tree structure has changed
         model.nodeStructureChanged(parent);
         path = path.pathByAddingChild(node);
         jTree1.scrollPathToVisible(path);
         //jTree1.repaint();    

    Yes, I've tried setSelectionPath(TreePath path) numerous times, but it does nothing to select the node on the tree! You can see from the code I submitted that it is there commented out.
    Ordinarily, when you click on a node on the tree it becomes the "active" node, evident because it becomes highlighted. But when I use setSelectionPath(TreePath path) method, giving it the path it needs, the node on the tree doesn't become the "active" node, therefore, not selected! Furthermore and subsequently, the rest of the code in the method createLeafNode() doesn't add a new node to the tree in the location specified by the TreePath object!
    If you have used setSelectionPath(TreePath path) before successfully I would be interested in seeing a small sample program demonstrating its use. It would have to prove to me that you can select a node in the tree without physically clicking on any node in the tree with the mouse cursor, and add a new child node to that selected node.
    I submit to you a small test program I put together that demonstrates the "typical setup". It requires the user to physically click on a node of the tree, then click on a button that adds a new node in the location of the selected node. If you can alter this program demonstrating that you can add a new node to the tree without my having to click on any node of the tree with my cursor, then I'll assign you the Duke Dollars and be forever humbled by your programming prowess.
    Thanks for keeping on top of this thread as I've tried everything I can think of to try and make my program work. If you need to ask any questions please ask away. Perhaps there is something about my program that I've not explained yet that you're not aware of that I should have included. At this point I can't see the forest for the trees.
    Alan
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JTree;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class AddNodeExample extends JFrame implements ActionListener
      JTree jTree1 = null;
      DefaultTreeModel model = null;
      DefaultMutableTreeNode rootNode = null;
      JScrollPane jScrollPane1 = null;
      JLabel status = new JLabel("Status:");
      TreePath path = null;
      JButton add = new JButton("Add new node");
      public static void main(String[] args)
        AddNodeExample example = new AddNodeExample();
        example.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      public AddNodeExample()
        super("Add Node To JTree Example");
        setSize(400, 300);
        jScrollPane1 = new JScrollPane();
        add.addActionListener(this);
        DefaultMutableTreeNode[] boys = new DefaultMutableTreeNode[6];
        boys[0] = new DefaultMutableTreeNode("Harry");
        boys[1] = new DefaultMutableTreeNode("Tom");
        boys[2] = new DefaultMutableTreeNode("Jake");
        boys[3] = new DefaultMutableTreeNode("Brian");
        boys[4] = new DefaultMutableTreeNode("Alan");
        boys[5] = new DefaultMutableTreeNode("Guy");
        DefaultMutableTreeNode[] girls = new DefaultMutableTreeNode[6];
        girls[0] = new DefaultMutableTreeNode("Debbie");
        girls[1] = new DefaultMutableTreeNode("Jane");
        girls[2] = new DefaultMutableTreeNode("Sally");
        girls[3] = new DefaultMutableTreeNode("Jessica");
        girls[4] = new DefaultMutableTreeNode("MoonUnit");
        girls[5] = new DefaultMutableTreeNode("Sara");
        rootNode = new DefaultMutableTreeNode("Students");
        DefaultMutableTreeNode Boys = new DefaultMutableTreeNode("Boys");
        DefaultMutableTreeNode Girls = new DefaultMutableTreeNode("Girls");
        //Fill up the node for boys
        for(int i = 0; i < boys.length; i++)
          Boys.add(boys);
    //Fill up the node for girls
    for(int i = 0; i < girls.length; i++)
    Girls.add(girls[i]);
    //add Boys and Girls to rootNode
    rootNode.add(Boys);
    rootNode.add(Girls);
    model = new DefaultTreeModel(rootNode);
    jTree1 = new JTree(model);
    jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    jTree1.putClientProperty("JTree.lineStyle", "Angled");
    jTree1.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent event)
         path = event.getPath();
    DefaultMutableTreeNode node = getTreeNode(path);
    status.setText("Selected: " + (String)node.getUserObject());     
    jScrollPane1.getViewport().add(jTree1, null);
    getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    getContentPane().add(add, BorderLayout.NORTH);
    getContentPane().add(status, BorderLayout.SOUTH);
    setVisible(true);
    public DefaultMutableTreeNode getTreeNode(TreePath path)
    return (DefaultMutableTreeNode)(path.getLastPathComponent());
    public void actionPerformed(ActionEvent e)
    jTree1.repaint();
    if (path == null || path.getPathCount() < 1)
         return;
    DefaultMutableTreeNode treeNode = getTreeNode(path);
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("My New Node");
    treeNode.add(newNode);
    model.nodeStructureChanged(treeNode);
    path = path.pathByAddingChild(newNode);
    jTree1.scrollPathToVisible(path);                    

  • Drop on a Tree Node - Help!

    On a drop on a tree node, I'd like to get the item that is
    being dropped on.
    Tree object being dropped on: event.currentTarget
    Index of node in tree being dropped on:
    event.currentTarget..calculateDropIndex(event); where event is the
    DragEvent
    dropTarget is a great name for a method that would do this,
    but it returns a display object.
    Some ideas:
    1. Use the index to somehow go through the XML data provider.
    I don't think this is the right way - the XML structure is not list
    based.
    2. The Tree creates a list from the XML. How can I leverage
    that and get the item for a given node index? dropTarget seems like
    the right term, but it returns a display object.
    3. tree.selectedItem and tree.Selected Items return null and
    an array of null, so I can't use that either.

    Hello Brian,
    thanks for your reply.
    The benefit of focusing a node in the tree is the following:
    If a person only uses the keyboard to navigate (e.g. because of him/her being blind) expands a tree node, he expects the focus still being on the expanded tree node afterwards. But if a roundtrip to the server happens (because of a executed onClick-event) the focus after the reload is at the beginning of the page again. Thus the blind person hast to TAB through the whole page again until he reaches the tree node he has expanded.
    I use the com.sapportals.htmlb.* package for the htmlb-elements.
    Almost all elements are underclasses of com.sapportals.htmlb.Component, but Treenode is not.
    I use a model to create tree nodes. TreeNodes are created like this in the Model:
      mComponentsNode = new TreeNode(COMP_NODE_ID);
      mComponentsNode.setComponent(new TextView(COMP_NODE_TEXT));
      mComponentsNode.setOnNodeClick(MODE_ON_CLICK_EVENT);
      mComponentsNode.setOnNodeExpand(TREE_NODE_EXPAND_EVENT);
      mComponentsNode.setOnNodeClose(TREE_NODE_CLOSE_EVENT);
      mComponentsNode.setTooltip(COMP_NODE_TOOLTIP);
      mComponentsNode.setOpen(true);
      mHomeNode.addChildNode(mComponentsNode);
    In the JSP the tree is created like this:
      <hbj:tree id="configTree"
        title=""
        rootNode="configTree"
        rootNodeIsVisible="false">
      </tree>
    Do you have any idea?
    Thanks!
    Regards,
    Bastian

  • How do i expand all the nodes in a jtree

    Hi,
    I am working on a project where i need to expand all the nodes of a jtree i have tried a few different ways but it never seems to expand all the nodes..
    I would be very greatful if someone could point me in the right direction
    cheers
    Mary

    you could use the following method that expands nodes recursively
    expandNode( myTree, myRootNode, new TreePath( myRootNode ) );
    public static void expandNode( JTree tree, TreeNode node, TreePath path ) {
        tree.expandPath( path );
        int i = node.getChildCount( );
        for ( int j = 0; j< i; j++ ) {
            TreeNode child = node.getChildAt( j );
            expandNode( tree, child , path.pathByAddingChild( child ) );
    }

  • 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 cut, copy and paste a tree node in JTree?????

    Hi, Java GUI guru. Thank you for your help in advance.
    I am working on a File Explorer project with JTree. There are cut, copy and paste item menus in my menu bar. I need three EventAction methods or classes to implements the three tasks. I tried to use Clipboard to copy and paste tree node. But I can not copy any tree node from my tree.
    Are there any body has sample source code about cut, copy, and paste for tree? If possible, would you mind send me your sample source code to [email protected]
    I would appreciate you very very much for your help!!!!
    X.G.

    Hi, Paul Clapham:
    Thank you for your quick answer.
    I store the node in a DefaultMutableTreeNode variable, and assign it to another DefaultMutableTreeNode variable. I set up two classes (CopyNode and PasteNode). Here they are as follows:
    //CopyNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class CopyNode implements ActionListener{
    private TreeList jtree;
    String treeNodeName;
    TreePath currentSelection;
    DefaultMutableTreeNode currentNode;
    public CopyNode(TreeList t){
    jtree = t;
    public void actionPerformed(ActionEvent e){
    currentSelection = jtree.tree.getSelectionPath();
    if(currentSelection != null){
    currentNode = (DefaultMutableTreeNode)(currentSelection.getLastPathComponent());
    treeNodeName = currentNode.toString();
    //PasteNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class PasteNode extends DefaultMutableTreeNode{
    private TreeList jtree;
    CopyNode copyNode;
    public PasteNode(TreeList t){
    jtree = t;
    copyNode = new CopyNode(t);
    public DefaultMutableTreeNode addObject(Object child){
    DefaultMutableTreeNode parentNode = null;
    TreePath parentPath = jtree.tree.getSelectionPath();
    if(parentPath == null){
    parentNode = jtree.root;
    else{
    parentNode = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
    return addObject(parentNode, child, true);
    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible){
    DefaultMutableTreeNode childNode = copyNode.currentNode;
    if(parent == null){
    parent = jtree.root;
    jtree.treemodel.insertNodeInto(childNode, parent, parent.getChildCount());
    if(shouldBeVisible){
    jtree.tree.scrollPathToVisible(new TreePath(childNode.getPath()));
    return childNode;
    I used these two classes objects in "actionPerformed(ActionEvent e)" methods in my tree:
    //invoke copyNode
    copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(copyNode);
    //invoke pasteNode
    pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    pasteName.addObject(copyName.treeNodeName);
    When I run the drive code, making a copy some node from my tree list, I got bunch of error messages.
    Can you figour out what is wrong in my two classes? If you have sample code, would you mind mail me for reference.
    Thank you very much in advance.
    X.G.

  • JTree and selected tree node

    I am allowing the user to search for a node in a JTree. I can find the node and progamatically expand and select the node. What I would like to do next is find the x,y coordinates of this selected node so I can use Robot to move the mouse to this node. I have hover help which is chock full of information in HTML describing this node, however, the user now is required to move the cursor to this selected node to see the hover help.
    Any help would be appreciated.

    Hi ,
    try this
    jlabel.setIcon( null ) ;

Maybe you are looking for

  • Error in BPM worklist login page

    Hi Experts, I have created one bpel process which invokes task manager for approving or rejecting the leave request. I ve successfully deployed the bpel process and also able to test approve or reject the leave request . But i am facing one error whe

  • Display current date and time

    Hello everyone, how can I display the current date and time in a simple text field? Best Mobilizer

  • Mavericks running slow

    I have a early 2011 MacBook Pro 17", 2.2 GHz i7, 16gb RAM, and I have installed Mavericks OS. After the upgrade, I find that my Mac is running pretty sluggish and slow, definitely not your typical Apple product. While view my photos through Finder, I

  • How do I reset my shape tools in CS5?

    All of my shapes look like I skewed them. I can't draw a perfect circle or square using my tools. They look like this. Additionally, my cursor has a vertical line with an arrow to the side of it whenever I'm about to draw a shape. Did I accidentally

  • 5.1 surround on 3/9 Audigy 2 Dri

    So my 5. surround either works or doesn't depending on where you look. When I go through the standard Control Panel and click sound and run a test through there, I get sound from my rears?When I go through the CL Speaker Settings and run a test, I ge