Using depth first traversal to add a new node to a tree with labels

Hello,
I'm currently trying to work my way through Java and need some advice on using and traversing trees. I've written a basic JTree program, which allows the user to add and delete nodes. Each new node is labelled in a sequential order and not dependent upon where they are added to the tree.
Basically, what is the best way to add and delete these new nodes with labels that reflect their position in the tree in a depth-first traversal?
ie: the new node's label will correctly reflect its position in the tree and the other labels will change to reflect this addition of a new node.
I've searched Google and can't seem to find any appropriate examples for this case.
My current code is as follows,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class BasicTreeAddDelete extends JFrame implements ActionListener
    private JTree tree;
    private DefaultTreeModel treeModel;
    private JButton addButton;
    private JButton deleteButton;
    private int newNodeSuffix = 1;
    public BasicTreeAddDelete() 
        setTitle("Basic Tree with Add and Delete Buttons");
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
        treeModel = new DefaultTreeModel(rootNode);
        tree = new JTree(treeModel);
        JScrollPane scrollPane = new JScrollPane(tree);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        JPanel panel = new JPanel();
        addButton = new JButton("Add Node");
        addButton.addActionListener(this);
        panel.add(addButton);
        getContentPane().add(panel, BorderLayout.SOUTH);
        deleteButton = new JButton("Delete Node");
        deleteButton.addActionListener(this);
        panel.add(deleteButton);
        getContentPane().add(panel, BorderLayout.SOUTH);    
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 300);
        setVisible(true);
    public void actionPerformed(ActionEvent event) 
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
        if(event.getSource().equals(addButton))
            if (selectedNode != null)
                // add the new node as a child of a selected node at the end
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node" + newNodeSuffix++);
                  treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                  //make the node visible by scrolling to it
                TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                TreePath path = new TreePath(totalNodes);
                tree.scrollPathToVisible(path);               
        else if(event.getSource().equals(deleteButton))
            //remove the selected node, except the parent node
            removeSelectedNode();           
    public void removeSelectedNode()
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
        if (selectedNode != null)
            //get the parent of the selected node
            MutableTreeNode parent = (MutableTreeNode)(selectedNode.getParent());
            // if the parent is not null
            if (parent != null)
                //remove the node from the parent
                treeModel.removeNodeFromParent(selectedNode);
    public static void main(String[] arg) 
        BasicTreeAddDelete basicTree = new BasicTreeAddDelete();
}      Thank you for any help.

> Has anybody got any advice, help or know of any
examples for this sort of problem.
Thank you.
Check this site: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html

Similar Messages

  • JTree: HOW TO add a new node

    Hi everybody,
    Im going to try to be clear...
    My problem is the following: I am a beginner using JTree and what I want to do is to add a new node in a certain position in my JTree. I would be very grateful if apart from explanation, any of you could provide me with a piece of code.
    Let us think that my tree has the root and some first-level children called group 1, ..., group n. Every group has some children called rulemodule 1, ..., rulemodule m. And every rulemodule has some children called rule 1, ..., rule j.
    An example of the visual look of my jtree:
    root
    __ group 1
    ____ rulemodule 1.1
    ______ rule 1.1.1
    ____ rulemodule 1.2
    ______ rule 1.2.1
    ______ rule 1.2.2
    ______ rule 1.2.3
    __ group 2
    ____ rulemodule 2.1
    ______ rule 2.1.1
    ____ rulemodule 2.2
    ______ rule 2.2.1
    Then, let us say that what I want is to add a new rule in the position where it is in this moment rule 1.2.2 (so the rule that was 1.2.2 before would be now 1.2.3, and the one that was 1.2.3 would be now 1.2.4). So I know the name of the group, the name of the rulemodule and the position of the new rule. How could I do that?
    In order to build the JTree I have the following statements:
    TreeNode treeNode = fillTheTree(ruleModulePart.config.getRuleModules()); This function actually builds the tree.
    jTreeModel = new DefaultTreeModel(treeNode);
    jTree = new JTree(jTreeModel);
    Thanks a lot to everybody!
    Fran.

    Thanks a lot for your answer Maxideon,
    Well, I think that I did not explained it the problem very well...
    The example of the tree was just that, an example, but the tree does not look like that. I just wanted to show that the tree has 3 levels of depth.
    The declaration of the function would actually be like that:
    public void UpdateJTreeWithNewRule (String groupName, String ruleModuleName, String newRuleName, int positionOfNewRule) {
    }So I think that I would need to do first a search to find the position of the "group" which corresponds to that 'groupName' and after that the position of the "rulemodule" which corresponds to that 'ruleModuleName'. And then add the 'newRuleName' in the position 'positionOfNewRule' inside that "rulemodule".
    Thanks a lot again,
    Fran.

  • SQL Server Distributed Partitioning Views how to add a new node online

    We are using distributed partitioning views in SQL Server 2012 Enterprise Edition for scaling out our data across more than one servers. Now we faced to question how to add a new node (server) into the scale outed db servers system without sending the servers
    down, so our users will be able to use them during the process as well.
    For example we have 4 servers with scaled out data. When we add the new empty server, the CHECKINGs for the partitioning columns should be reorganized. But during the process the partitioning views are not working.
    The High Availability, Always On or Failover Cluster approaches seem are not resolve the problems.
    So my question is how to add new node online?
    KH

    Thank you Erland for the reply.
    Yes, it's sounds as possible solution but has some not resolvable nuance in it. Let's say we copied some data from Node5 to new added Node6. Let's assume in Node5 we had data in Table1 with partitioning column's values 100,101,102,103,104,105,106.  Now
    we want to copy part of the rows with partitioning column's values 103,104,105,106 from Node5.Table1 into Node6.Table1. With this Node5 will contain less data and will work more quickly (less IO, less CPU usage etc), and the rest data will be contained on
    Node6. But because of Node5 is already in use, the Node5.Table1 contains CHECK CONSTRAINT = ParttionColumn should be from 100 up to 106. This is check for Node5. The Distributed Partitioning Views are already using the CHECKs to identify what server should
    be used to get data from.
    Now when we copied part of the Node5.Table1 rows to Node6.Table1 the views are still using the 103-106 rows from Node5.Table1 because the CHECK points there. Then we include the newest Node6.Table1 in the distributed partitioning views. OK, but we should
    set some CHECK on new Node6.Table1 which will be used by views. We can't set intersecting checking like Node5 has CHECK 100-106 and Node6 has CHECK 103-106. We also can't edit Node5 check and set it 100-102 untill the data will be removed in it. But this means
    that the data will not be available during the execution. 
    So, any ideas ?
    KH

  • I need to add a new node to RAC Oracle 10g R2

    I need to add a new node to RAC Oracle 10g R2.
    what is the best mode.
    cloning or step by step?
    SO: Solaris 64bit
    Message was edited by:
    ACS

    Hi All,
    I get the following error eventhough I have followed the instruction for Solaris R2. The instruction is enclosed. Please Advise! Thanks.
    /app/cluvfy/runcluvfy.sh stage -post hwos -n nod1 -verbose
    Result: User equivalence check failed for user "oracle".
    ERROR:
    User equivalence unavailable on all the nodes.
    Verification cannot proceed.
    Post-check for hardware and operating system setup was unsuccessful on all the nodes.
    =========================
    1. Log in as the oracle user.
    2. If necessary, create the .sshdirectory in the oracle user’s home directory and
    set the correct permissions on it:
    $ mkdir ~/.ssh
    $ chmod 700 ~/.ssh
    3. Enter the following commands to generate an RSA key for version 2 of the SSH
    protocol:
    $ /usr/bin/ssh-keygen -t rsa
    At the prompts:
    ¦ Accept the default location for the key file.
    ¦ Enter and confirm a pass phrase that is different from the oracle user’s
    password.
    This command writes the public key to the ~/.ssh/id_rsa.pub file and the
    private key to the ~/.ssh/id_rsafile. Never distribute the private key to anyone.
    4. Enter the following commands to generate a DSA key for version 2 of the SSH
    protocol:
    $ /usr/bin/ssh-keygen -t dsa
    At the prompts:
    ¦ Accept the default location for the key file
    Pre-Installation Tasks 2-11
    Creating Required Operating System Groups and User
    ¦ Enter and confirm a pass phrase that is different from the oracle user’s
    password
    This command writes the public key to the ~/.ssh/id_dsa.pub file and the
    private key to the ~/.ssh/id_dsa file. Never distribute the private key to
    anyone.
    Add keys to an authorized key file: Complete the following steps:
    1. On the local node, determine if you have an authorized key file
    (~/.ssh/authorized_keys). If the authorized key file already exists, then
    proceed to step 2. Otherwise, enter the following commands:
    $ touch ~/.ssh/authorized_keys
    $ cd ~/.ssh
    $ ls
    You should see the id_dsa.pub and id_rsa.pubkeys that you have created.
    2. Using SSH, copy the contents of the ~/.ssh/id_rsa.puband
    ~/.ssh/id_dsa.pubfiles to the file ~/.ssh/authorized_keys, and provide
    the Oracle user password as prompted. This process is illustrated in the following
    syntax example with a two-node cluster, with nodes node1 and node2, where the
    Oracle user path is /home/oracle:
    [oracle@node1 .ssh]$ ssh node1 cat /home/oracle/.ssh/id_rsa.pub >>
    authorized_keys
    oracle@node1’s password:
    [oracle@node1 .ssh]$ ssh node1 cat /home/oracle/.ssh/id_dsa.pub >>
    authorized_keys
    oracle@node1 .ssh$ ssh node2 cat /home/oracle/.ssh/id_rsa.pub >>
    authorized_keys
    oracle@node2’s password:
    [oracle@node1 .ssh$ ssh node2 cat /home/oracle/.ssh/id_dsa.pub
    authorized_keysoracle@node2’s password:
    Note: Repeat this process for each node in the cluster                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Trying to add a new node to OAS

    I'm trying to add a new node to our OAS server, and it always fails. Any hints on what I might be doing wrong?

    every entry in an ldap directory must have some mandatory attributes, e.g. "objectClass". which objectclass your entry should belong to? add the objectClass-attribute to your entry!
    Regards!
    Rainer

  • Add a new employee - Connection is busy with results for another command

    Hi all,
    I try to add a new employee in my SAP Business One system, but I get an error message like that : [Microsoft][SQL Native Client] Connection is busy with results for another command * (HEM5) (HEM5)
    So I try to see if I get the same message when I update an employee, and I don't get this message.
    Do you have an idea, why I get this error message when I add a new employee ?
    Message was edited by:
            Marc Riar

    Hello,
    I am afraid there maybe two users / workstations using the same user code and one of them is creating (add) and other is update. Try to ask the users/wrokstations.
    Another way out is try to run this query :
    select * from HEM5
    Rgds,
    JM
    http://groups.yahoo.com/group/SBO_Knowledge_Village
    [email protected]

  • How to add a new node into existing XML Document

    I have a very simple question. I use XML as input argument for PL/SQL procedure that inserts data into the corresponding table. All I have to do is to add a new tag for Primary Key column and put sequence.NEXTVAL - value into it.
    <ROWSET>
    <ROW>
    -- Add <ID_table_name> value </ID_table_name> ??????
    <FIELD1>data1</FIELD1>
    <FIELD2>data1</FIELD2>
    </ROW>
    </ROWSET>
    I've parsed XML, but I couldn't find the way how to insert the new NODE.
    If you know how to use packages XMLDOM, XMLParser for this purpose, please help me!
    Oracle version 8.1.7

    DOMParser parser=new DOMParser();
    XMLDocument xmlDocument=parser.getdocument();
    Node node=xmlDocument.selectSingleNode("/ROWSET/ROW");
    Element element=xmlDocument.createElement(String tagName)
    node.appendChild(element);

  • Reconfiguring a conventional cluster (add a new node) must there be outage?

    hi *,
    i just wanted to know if some of you know if a conventional cluster e.g. can be expaanded without any outages?
    questions like do i have to shutdown the master broker?
    or
    do i have to shut down every node then ?
    or
    do i have to shut down everything?
    does anyone of you know the details`?
    is a updated broker config file recognized by the running processes?
    regards chris

    hi *,
    i have already found almost all the things i needed in http://docs.sun.com/app/docs/doc/820-4916/gbnlp?l=en&q=sun+java+system+message+queue&a=view
    regards chris

  • Cannot add a new SHIP_TO address to a exist customer by using Interface

    Hi,
    I am encountered an error when i am using Customer Import Interface to add a new SHIP_TO address to a exist customer,
    the template format of the Excel i used like below: <will insert to table: ra_customers_interface_all>
    Customer Num. | Customer Name | Site Name | Address | Site Use Code | ... ...
    1 | oracle | AA | address1 | BILL_TO |... ...
    1 | oracle | AA | address1 | SHIP_TO |... ...
    1 | oracle | AB | address2 | SHIP_TO |... ...
    I am able to import top 2 rows correctly, as those 2 sites with same Site Name AA;one is BILL_TO site and another one is SHIP_TO address; I tested for few customers, it can run correncty if the BILL_TO address and SHIP_TO address are same.
    But when running import for the third row to add another SHIP_TO address<AB&address2> to the exist customer<1&oracle>,the error raised, it gave error message like below:
    The Customer Number has been used by another customer,import failed !
    I am not too clear about this error,i just want to add a SHIP_TO address to the exist customer<1&oracle> and don't want to create a new customer.
    what should i pay attention to? please give me some tips,,,,,,
    Thanks a lot...
    Rock Lei

    Did you ever get a response or resolution? I have the same issue. Did you get a fix for this? If so, could you share?
    Thanks

  • I need to add a new report to the application that is done using visual studio and SSRS and SQL Server 2008

    I have an application that is done using SSRS on visual studio and it connects to the report server on SQL server 2008 environment.
    I've been changing the existing reports using visual studio 2008 and modifying the reports on the report server. How do I add a new report to the application ? I created a new report and deployed it on the report server but it didn't show up in the application.
    I can access the application source code on visual studio 2010 and TFS (Team Foundation). Thanks. 

    Hi,
    I have a question. This application retrieves SSRS reports from the report sever. When I download the reports
    from the SQL Server I can open them in visual studio 2008 but they don't open in visual studio 2010. I can access the application files on visual studio 2010 and team foundation server 2010. I was unable to open team foundation server 2008 on visual studio
    2008. The issue is that I am unable to add a report with a new name to the application. I use visual studio 2008 to deploy the reports on the report server but it has to be the same name to be able to run the report from the application. I can deploy any report
    on the report server but I can't access it from the application unless it has to be the same name as the present reports. If I keep the report the same name then it will replace the old report and the new report will run from the application. But only if it's
     the same name. I guess when I add a new report to the application with a new name I am supposed to add a definition in the application C sharp files  on visual studio 2010 so that the new report will show in the application. What's your opinion
    ? I have attached 2 images of the application and team foundation server 2010 and the report server.
    Thanks. 

  • Add a new column and the value

    I want to add a new column to a table with a single value for all rows of this column. for example, add a new column called 'sid' with the value of 'dbp'. can I use this statement?
    alter table ... add sid varchar(8) 'dbp';
    or I have to add first then update?

    SQL> alter table blah add (sid varchar2(8) default 'dbp');
    Table altered.
    SQL> select * from blah;
                    COL1 SID
                       1 dbp
                       2 dbp
                       3 dbpMessage was edited by: SomeoneElse
    (used OP's column name)

  • When to go for Breadth first search over depth first search

    hi,
    under which scenarios breadth first search could be used and under which scenarios depth first search could be used?
    what is the difference between these two searches?
    Regards,
    Ajay.

    No real clear-cut rule for when to use one over the other. It depends on the nature of your search and where you would prefer to find results.
    The difference is that in breadth-first you first search all immidiate neighbours before searching their neighbours (sort of like preorder traversal). Whereas in depth-first you search some random (or otherwise selected) neighbour and then a neighbour of that node until you can't go deeper (i.e., you've searched a neighbour that has no other neighbours). This probably isn't a very clear explanation, perhaps you'll find this more helpful: http://www.ics.uci.edu/~eppstein/161/960215.html
    If you would prefer to find results closer to the origin node, breadth first would be better. If you would prefer to find results further away use depth first.

  • OIM-SOA CLUSTER add new node

    Hi All,
    i need to add a new node to my cluster OIM/SOA.
    My env is:
    1) cluster 6 nodes whit SOA and OIM
    2) the first node have a console weblogic server admin
    3) More patchs are installed on
    Look at this picture: [https://dl.dropboxusercontent.com/u/9054488/OIM-SOA-CLUSTER.jpg]
    I found the proc to doc.id [e10106 pag.523 - 8.9.3.20.1 Scaling Up Oracle Identity Manager] but I don't understand if it is applicable to systems already patched.
    There is a procedure already proven and clearer?
    Thanks.

    In order to add a new node, you must first install all the applications/modules in your middleware home. Install the same patches on top of those. Then using the packEnv scripts to pack up the domain, and then unpack it to your new host.
    From the weblogic console, use the option to clone your app server and create a new machine for your new machine instance. Startup your node manager on your new machine, and start your app server.
    You just need to make sure to do all the same modifications, if you have any, to your new server, like deploy jar files, make changes to UI interface, etc.
    -Kevin

  • ICS 2.x: How do I add a new timezone?

    How do I add a new timezone in iPlanet Calendar Server (iCS) 2.x?
    <P>
    Use the following steps to add a new timezone:<BR>
    <P>
    <OL>
    <LI>Create a new <B>timezone definition</B>. <B>Timezone definitions</B> are
    are specified as iCalendar objects, as defined in RFC 2445. The definition for
    the "Australia/Perth" timezone would appear as follows:<BR><P>
    BEGIN:VTIMEZONE
    TZID:Australia/Perth
    BEGIN:STANDARD
    DTSTART:19970101T000000
    TZOFFSETFROM:+0800
    TZOFFSETTO:+0800
    TZNAME:WST
    TZNAME:CTT
    END:STANDARD
    END:VTIMEZONE
    <P>
    <LI>Add the timezone definition to the file<BR>
    <P>
    loadpoint
    /CalendarServer/cal/bin/data/timezones_libnls.ics
    <P>
    <LI>Restart iCS.
    <P>
    <LI>Add the following line to the file
    loadpoint/CalendarServer/cal/uicust/en/tz_i18n.js:<BR>
    <P>
    tzList[tzList.length] = t('', 'Australia/Perth');
    <P>
    <LI>Add the following line to the file
    loadpoint/CalendarServer/cal/uicust/en/tz_fs.html:<BR>
    <P>
    tzList[tzList.length] = t('', 'Australia/Perth');
    </OL>

    You need to log into your emali on your computer and create the new folder from there.

  • Depth First Search w/o Recursion

    I am trying to use Depth First Search for 2-D maze, and I was just wondering if there was a straight forward and easy way of doing DFS of a maze without using recursion. Or is recursion the really only way you do DFS without invoking a lot of messy variables to hold temporary information.

    itereation instead of recursion...can you be a little more discriptive.
    For recursion I can understand how it works because when you pop out of one recursive cycle you got to the next command. So basically
    move{
    if you can
    go left
    move()
    go right
    move()
    go up
    move()
    go down
    move()
    else
    pop out of recursion
    hopefully this pseudocode makes some sense. But absically lets say with my maze I go right 3 times then can't go right anymore...well when that happens it will try to go right, because after calling move() under "go left" the next step would just be to go left. But I don't see how this can be done iteratively. If somebody can explain it pseudocode that would be cool too.

Maybe you are looking for

  • FM Execution :

    Hi Everbody, Am using the FM "BAPI_DOCUMENT_CHECKIN2" to checkin the file in to DMS system. Backend Systen ERP is configured with DMS system , When FM of above is executed from backendsystem file gets attached. But Scenario gets different when i use

  • Connecting 2 15" ADC Displays to G5

    I already have a 15" ADC display & have another one on the way. I require the use of a seperate display for using music software etc. Can anyone tell me how I can connect the extra display to my G5? Do I need an extra connection?

  • Clear WLC config (on WiSM v4.0.179.8)

    I did, clear config, then reset system (without saving). Then WLC rebooted and went into setup dialog as expected. What was not expected was that the, User: Password: were not back to default of admin, admin but had retained their easlier settings. W

  • Custom tag paths

    I have serveral CF servers running. Is it possible to map to custom tags on one server from another server without a share between the servers? Or even with shared drives? What are the security issues if you create a share? Thanks Mark

  • [SOLVED] Question about Warzone-SVN revision upgrade method

    Hi all, I have installed warzone-svn from AUR using yaourt. My question is simple, how do I upgrade when the next revision in svn repository is out? Do I upgrade using # yaourt -Syu or is there something else i will have to do? Regards, J0sh Last edi