Traversing SceneGraph

Hi!
I would really appriciate if someone could help me with this.
I have to travers all the nodes in one tree, from one BranchGroup, to all the leaf nodes in the tree, to get the Shape3D generated by a 3ds-loader.
I would like a method that takes the BranchGroup as argument and then for all the leaf nodes sets the capability bits for each. Does anyone have that code or have a simple example how I should do this?
Regards,
Henrik

This should be pretty straightforward. If you have the branch group, then you are all set. Simply traverse the scene graph recursively, using leaf nodes as your base case for returning. So your algorithm will look something like this:
public void findAllShape3DNodes( final Node parentNode )
     int numChildren = parentNode.numChildren();
     for( int i=0; i<numChildren; ++i )
          Node node = parentNode.getChild( i );
          if( node instanceof Shape3D )
              //  Do whatever you need to do to this Shape3D
          else
              findAllShape3DNodes( node );
}That's the general gist of the algorithm. Of course, you will have to modify it to suit your needs, but in general that is the idea you want to follow. So the parentNode parameter to the method will be the branch group that you picked. You send that branch group to the method and it iterates over its child nodes, searching for Shape3D objects. If it finds a Shape3D object, then does whatever you wanted to do to that node. If it isn't a Shape3D node, then it must be some other kind of node (might want to check that its not any other kind of leaf node, but with this algorithm it shouldn't make a difference since a leaf node has no children). If its some other kind of node, recur on that node and iterate over all of its children, and so on.
Hope that helps!
Cheers,
Greg

Similar Messages

  • Advanced:   How to traverse a tree representation in PL/SQL (procedure)?

    I am looking to write a method that will create a collection of records, each of which represents a node in a tree.
    TYPE t_all_folders IS TABLE OF get_all_folders%ROWTYPE INDEX BY PLS_INTEGER;
    v_all_folders t_all_folders;
    so first need help in figuring out what the cursor 'get_all_folders' would look like
    I have a folder structure represented in a database that is used basically to show visually
    (with a front end app) a folder structure (much like a folder structure in a file system).
    So each row has an entry in the 'folders' table like do:
    table folder:
         column           column
         folder_id          name
         1                    folder1               <= say this is a root folder
         2                    folder2               <= say this is a root folder
         3                    folder3               <= say this is a root folder
         4                    folder1a          <= all below are child folders..
         5                    folder1b
         6                    folder1c
         7                    folder1aa
         8                    folder1ab
         There is nothing in this table that indicates a hiearchy.
    The hiearchy is represented by another single table with two columns
    (I cannot change this, it is what it is)
    There is no left node or right node (not like a tree), just imagine sub folders.
    table: parent_child
         column          column
         parent_id     child_id
    such that visually when the tables are queried and the UI uses a folder icon to
    represent each row:
    it would look like this:
         folder1                              1
              - folder1a                         2
                   -folder1aa                    3
                   - folder1ab                    4
              - folder1b                         5
                   - folder1ba                    6
                   - folder1bb                    7
              - folder1c                         8
         folder2                              9
         folder3                              10
    I am attempting to create a query that will add to a collection folder records in the
    order above (1..10)
    In other words traverse the tree depth first going from:
              folder1 -> folder1a -> folder1aa -> folder1ab ->(back out to next level) folder1b -> folder1ba -> folder1bb -> folder1c
              then add folder2 (and traverse down that hiearch if needed)
              and then add folder3 to the colleciton and traverse down that hiearchy if there is one
              and continue adn so on.
              The requirement is to have them added to the collection in that order and when I iterate through the collection,
              they would of course need to be pulled out in that order (so use vararray with a counter to iterate through
              after the collection has been created.
    After the collection has been created, I have to iterate in that specific order to create records in another table where there is a column that requires an integer value that is the 1... order they come out of the collection
    and then have to iterate again and do something else in that order (and then other things - all the while needing in that order).
    Edited by: user12200443 on Nov 19, 2012 11:49 AM

    awesome, thanks for the help.
    put this in 'schema.sql' and run to create a reference schema and data for the example
    drop sequence seq_folders;
    CREATE SEQUENCE seq_folders
    INCREMENT BY 1
    MINVALUE 1
    START WITH 1
    CACHE 1000;
    drop table folders;
    create table folders (
         folder_id number not null,
         name varchar2(20) not null
    drop table parent_child;
    create table parent_child (
         parent_id number not null,
         child_id number not null);
    -- creation order (in order to have parent)
    -- folder1
    -- folder2
    -- folder3
    -- folder1a
    -- folder1b
    -- folder1c
    -- folder1aa
    -- folder1ab
    -- folder1ac
    -- folder1aaa
    -- folder1aba
    -- folder1aab
    -- folder1abb
    -- folder1aac
    -- folder1abc
    -- Visual hiearchy
    -- folder1                              1
    --      folder1a                         2
    --           folder1aa               3
    --                folder1aaa          4
    --                folder1aab          5
    --                folder1aac          6
    --           folder1ab               7
    --                folder1aba          8
    --                folder1abb          9
    --           folder1ac               10
    --      folder1b                         11
    --      folder1c                         12
    -- folder2                              13
    -- folder3                              14
    --- insert folders
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder2');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder3');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1a');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1b');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1c');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1aa');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1ab');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1ac');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1aaa');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1aba');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1aab');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1abb');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1aac');
    insert into folders(folder_id, name) values(seq_folders.nextval, 'folder1abc');
    commit;
    -- setup hiearchy
    insert into parent_child(parent_id, child_id) values (0, (select folder_id from folders where name = 'folder1'));
    insert into parent_child(parent_id, child_id) values (0, (select folder_id from folders where name = 'folder2'));
    insert into parent_child(parent_id, child_id) values (0, (select folder_id from folders where name = 'folder3'));
    -- 1a,1b,1c
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1'), (select folder_id from folders where name = 'folder1a'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1'), (select folder_id from folders where name = 'folder1b'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1'), (select folder_id from folders where name = 'folder1c'));
    -- aa,ab,ac
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1a'), (select folder_id from folders where name = 'folder1aa'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1a'), (select folder_id from folders where name = 'folder1ab'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1a'), (select folder_id from folders where name = 'folder1ac'));
    -- aaa,aba,aab
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1aa'), (select folder_id from folders where name = 'folder1aaa'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1aa'), (select folder_id from folders where name = 'folder1aab'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1aa'), (select folder_id from folders where name = 'folder1aac'));
    -- aba,abb,abc
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1ab'), (select folder_id from folders where name = 'folder1aba'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1ab'), (select folder_id from folders where name = 'folder1abb'));
    insert into parent_child(parent_id, child_id) values ((select folder_id from folders where name ='folder1ab'), (select folder_id from folders where name = 'folder1abc'));
    commit;
    then run this to get the error message
    WITH joined_data     AS
         SELECT     f.folder_id,     f.name,     pc.parent_id
         FROM     folders     f
         JOIN     parent_child     pc ON pc.child_id = f.folder_id
    SELECT     j.*,     ROWNUM     
    AS r_num
    FROM joined_data     j
    START WITH     parent_id =0
    CONNECT BY     parent_id= PRIOR child_id
    ORDER SIBLINGS BY     name;
    thanks for the help, hopefully I can find a way to read the rows/record into a data structure (does not have to be a single sql statement - can be anything I can do in PL/SQL.
    Edited by: user12200443 on Nov 19, 2012 5:55 PM

  • How can i traverse between files in a directory

    how can i traverse between files in a directory. I ahve seen in the site that isFile can be used to switch from one file to other but i didn't found such method. I am working in Eclipse. I would be thankful if u send me the solution.I mean the way to traverse

    listFiles() returns all the files in a directory. You can check if it is a file and read it. Read the API docs.
    If you have specific problem with your code, post the code and the problem description.

  • How can we prevent JTabbedPanes from transferring focus to components outside of the tabs during tab traversal?

    Hi,
    I noticed a strange focus traversal behavior of JTabbedPane.
    During tab traversal (when the user's intention is just to switch between tabs), the focus is transferred to a component outside of the tabs (if there is a component after/below the JTabbedPane component), if using Java 6. For example, if using the SSCCE below...
    import java.awt.BorderLayout;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TabbedPaneTest extends JPanel {
        public TabbedPaneTest() {
            super(new BorderLayout());
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            add(new JScrollPane(panel));
        private JPanel buildPanelWithChildComponents() {
            JPanel panel = new JPanel();
            BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
            panel.setLayout(boxlayout);
            panel.add(Box.createVerticalStrut(3));
            for (int i = 0; i < 4; i++) {
                panel.add(new JTextField(10));
                panel.add(Box.createVerticalStrut(3));
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneTest());
                    frame.pack();
                    frame.setVisible(true);
    ... Then we can replicate this behavior by following these steps:
    1) Run the program in Java 6; and then
    2) Click on a child component in any of the tabs; and then
    3) Click on any other tab (or use the mnemonic keys 'ALT + 1' to 'ALT + 4').
    At step 3 (upon selecting any other tab), the focus would go to the component below the JTabbedPane first (hence the printed message in the console), before actually going to the selected tab.
    This does not occur in Java 7, so I'm assuming it is a bug that is fixed. And I know that Oracle suggests that we should use Java 7 nowadays.
    The problem is: We need to stick to Java 6 for a certain application. So I'm looking for a way to fix this issue for all our JTabbedPane components while using Java 6.
    So, is there a way to prevent JTabbedPanes from passing the focus to components outside of the tabs during tab traversal (e.g. when users are just switching between tabs), in Java 6?
    Note: I've read the release notes between Java 6u45 to Java 7u15, but I was unable to find any changes related to the JTabbedPane component. So any pointers on this would be deeply appreciated.
    Regards,
    James

    Hi Kleopatra,
    Thanks for the reply.
    Please allow me to clarify first: Actually the problem is not that the child components (inside tabs) get focused before the selected tab. The problem is: the component outside of the tabs gets focused before the selected tab. For example, the JButton in the SSCCE posted above gets focused when users switch between tabs, despite the fact that the JButton is not a child component of the JTabbedPane.
    It is important for me to prevent this behavior because it causes a usability issue for forms with 'auto-scrolling' features.
    What I mean by 'auto-scrolling' here is: a feature where the form automatically scrolls down to show the current focused component (if the component is not already visible). This is a usability improvement for long forms with scroll bars (which saves the users' effort of manually scrolling down just to see the focused component).
    To see this feature in action, please run the SSCCE below, and keep pressing the 'Tab' key (the scroll pane will follow the focused component automatically):
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    public class TabbedPaneAutoScrollTest extends JPanel {
        private AutoScrollFocusHandler autoScrollFocusHandler;
        public TabbedPaneAutoScrollTest() {
            super(new BorderLayout());
            autoScrollFocusHandler = new AutoScrollFocusHandler();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            button.addFocusListener(autoScrollFocusHandler);
            JScrollPane scrollPane = new JScrollPane(panel);
            add(scrollPane);
            autoScrollFocusHandler.setScrollPane(scrollPane);
        private JPanel buildPanelWithChildComponents(int numberOfChildComponents) {
            final JPanel panel = new JPanel(new GridBagLayout());
            final String labelPrefix = "Dummy Field ";
            final Insets labelInsets = new Insets(5, 5, 5, 5);
            final Insets textFieldInsets = new Insets(5, 0, 5, 0);
            final GridBagConstraints gridBagConstraints = new GridBagConstraints();
            JTextField textField;
            for (int i = 0; i < numberOfChildComponents; i++) {
                gridBagConstraints.insets = labelInsets;
                gridBagConstraints.gridx = 1;
                gridBagConstraints.gridy = i;
                panel.add(new JLabel(labelPrefix + (i + 1)), gridBagConstraints);
                gridBagConstraints.insets = textFieldInsets;
                gridBagConstraints.gridx = 2;
                textField = new JTextField(22);
                panel.add(textField, gridBagConstraints);
                textField.addFocusListener(autoScrollFocusHandler);
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6 with auto-scrolling");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneAutoScrollTest());
                    frame.setSize(400, 300);
                    frame.setVisible(true);
    * Crude but simple example for auto-scrolling to focused components.
    * Note: We don't actually use FocusListeners for this feature,
    *       but this is short enough to demonstrate how it behaves.
    class AutoScrollFocusHandler extends FocusAdapter {
        private JViewport viewport;
        private JComponent view;
        public void setScrollPane(JScrollPane scrollPane) {
            viewport = scrollPane.getViewport();
            view = (JComponent) viewport.getView();
        @Override
        public void focusGained(FocusEvent event) {
            Component component = (Component) event.getSource();
            view.scrollRectToVisible(SwingUtilities.convertRectangle(component.getParent(),
                    component.getBounds(), view));
    Now, while the focus is still within the tab contents, try to switch to any other tab (e.g. by clicking on the tab headers, or by using the mnemonic keys 'ALT + 1' to 'ALT + 4')...
    ... then you'll notice the following usability issue:
    1) JRE 1.6 causes the focus to transfer to the JButton (which is outside of the tabs entirely) first; then
    2) In response to the JButton gaining focus, the 'auto-scrolling' feature scrolls down to the bottom of the form, to show the JButton. At this point, the tab headers are hidden from view since there are many child components; then
    3) JRE 1.6 transfers the focus to the tab contents; then
    4) The 'auto-scrolling' feature scrolls up to the selected tab's contents, but the tab header itself is still hidden from view (as a side effect of the behavior above); then
    5) Users are forced to manually scroll up to see the tab headers whenever they are just switching between tabs.
    In short, the tab headers will be hidden when users switch tabs, due to the Java 6 behavior posted above.
    That is why it is important for me to prevent the behavior in my first post above (so that it won't cause usability issues when we apply the 'auto-scrolling' feature to our forms).
    Best Regards,
    James

  • No longer able to traverse structure in sharepoint.

    I have the following folder structure in Sharepoint 2007
    Documents
    o  
    Region1
    Department A
    Joe's Reports
    Lisa's Reports
    Bob's Reports
    Department B
    Department C
    o  
    Region2
    o  
    Region3
    I have assigned permissions at the "Reports" level giving Joe Contribute rights to his folder, Lisa hers and so on.
    They do not have contribute or even read rights to the folders above them, but get assigned "limited access" permissions automatically.  
    Up until recently this has worked fine, they would be able to traverse the folders only to get to their Reports folder.
    No they can no longer traverse the folder structure, but if they click on a link that brings them directly to their folder, they still can see their files.
    I don't know what broke or changed so that they can no longer traverse the folder structure, but need to figure out how to fix this.  My organization is much larger than the example.
    Thank you in advance
    Stephen Hathaway

    They used to be able too access the region and department folders.  When assigning full rights
    to the sub folders, sharepoint automatically assigns limited access to the above folders so that they can browse through the tree structure to the folder that they need and have access to.
    This has worked flawlessly in the past - something happened a few months ago to cause this to change I haven't been able to figure out what has changed or
    maybe it was an update.
    Any other ides?
    Steve

  • How to traverse repository nodes in weblogic 8.1

    hi ,
    like binary search tree , how to traverse all node in repository .(can have many hierarchy node or content node ) .
    i have to traverse all content and hierarchy node .

    hi raj ,
    actually i have to traverse a node in repository 8.1 ,(like binary search tree).
    like u got a node then u have to check that how many content node /or hierarchy node it have , then check each of its content node/hierarchy node , then again check its child status (content/or hierarchy )same like binary search tree traversal .
    i try to make recursive code for that but not working properly , its searching at 2/3 levels , not at all levels .
    so if u can make recursive method for that i 'll appreciate u .
    thanks
    attaching my code for little help :
    public static void searchNode(Node node){
    if(node.getType()==Node.HIERARCHY){
    try{
    System.out.println( " Hierarchy content +node.getName());
    n=node.getChildren();
    for(int i=0;i<n.length;i++){
    System.out.println("child "+n.getName());
    searchNode(n[i]);
    catch(Exception e)
    System.out.println("");
    else //node.getType()==Node.CONTENT
    try{
         Property p[]=node.getProperties();
         for(int i=0;i<p.length;i++)
    if(p[i].getValue() !=null && p[i].getType() == Property.BINARY )
    System.out.println(" got property file " + p[i].getValue());
                             fname=p[i].getValue().toString();
    System.out.println(" adding "+fname+" these file to array list " );
    al.add(fname);
    System.out.println(" file added ");
    catch(Exception e)

  • Using XPath for DOM traversal

    This question falls into the category of 'I know it's possible, I just need to find the idom in Java'.
    I'm coming from a MSFT world were the DOM-centric model of XML processing makes heavy use of XPATH for node selection. Basically using the method element.selectNodes(XPathExpresson) allows one to quickly extract the relevant subset of the parsed tree in the DOM as a nodeList. I've become accustomed to using XML for all strucutured storage that doesn't require a full database.
    The W3C DOM Level 3 spec supports evaluateExpression() for this purpose, but I can't believe that Java developers are still using tree traversal waiting for the spec to be implemented. I suppose that I could use getNodesByTagName(), but this is a chainsaw, and I need a scalpel. Anyway, I'm trying to figure out how, exactly, this gets done in Java.
    I figure the following are possibilities:
    1) It's in JAXP and I missed it
    2) One or more of the XML parsers supports XPATH as an extention
    3) There's a common package that sits on top of the DOM Document.
    4) There's a standard way to apply and XSLT methods to the DOM document
    5) Something I've never thought of.
    This is a generalized problem for me, so I can't rely on object serialization, Java-XML data mapping, etc. Any guidance would be greatly appreciated.

    I've written a Config file reader for XML in java,
    and it extracts values using XPath. This is
    some of the code you'll need:
    imports:
    import javax.xml.transform.TransformerException;
    import org.w3c.dom.*;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.apache.xerces.parsers.DOMParser;
    import org.apache.xpath.XPathAPI;
    import org.apache.xpath.objects.*;
    Document doc=....;
    * returns a single DOM Node from the config file.
    public Node getNode(String xpath) throws ConfigException {
    try {
    return XPathAPI.selectSingleNode(doc, xpath);
    } catch (TransformerException e) {
    throw new ConfigException("Can't find '"+xpath+"' ("+e.getMessage()+")");

  • 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

  • How to remote desktop user can read, write ,modify and traverse folder but not execute?

    Now I ceate a user accout whis is user type and put him into remote desktop group.
    he can login this server by remote desktop.
    My server is windows 2003 but not in nt domain and  it is a workgroup computer.
    I want to limit him access right on one folder in which have many folders and .exe file.
    I only want he can read , write,modify file and traverse folder but not execute any .exe file.
    How can I implement this through NTFS.
    Please give me some advice.

    Hi,
    I think you could using advanced option to configure the file or folder permission:
    http://technet.microsoft.com/en-us/library/bb727008.aspx
    Regards.
    Vivian Wang

  • How to traverse a tree with a search

    I have a tree that has many leaves or nodes.
    I would like to have a search button where I put in a leaf or node name and it will go to the first occurrence on the tree and a next button that will take me to the next occurrence on the tree.
    The table I have looks like this.
    table name = PASS_NODE
    ID number,
    PARENT_ID NUMBER,
    NODE_NAME VARCHAR2(20)
    the sql code for the tree is:
    select "ID" id,
    "PARENT_ID" pid,
    CASE
    WHEN id = :P1_ID
    THEN '<span class="t1000url">'
    || node_name
    || ' >>'
    || '</span>'
    ELSE node_name
    END name,
    'f?p=&APP_ID.:1:&SESSION.::NO::P1_ID:'||id LINK,
    null a1,
    null a2
    from "#OWNER#"."PASS_NODE"
    order by NODE_NAME
    In the search text field the user will put in the NODE_NAME . I would like the search to traverse the tree by NODE NAME .
    Any ideas?

    I figured this out. In the "Search" process logic it was able to assign the value of the ID to the P1_ID page item.

  • Directory Traversal and Empty Directory Issue. Please Help!

    Hi
    I am building an application which is aimed at traversing the entire hard disk or a given folder and extract files from the folder, sub-folders and so on. I am able to currently traverse the disk and able to gain access to the files which are nested several layers of directories. The issue I am facing is that when I reach an empty directory, it throws a NullPointerException. I have tried using all kinds of methods like dir.exists() and have also tried to check for whether the number files in the directory is > 0, but the exception is still bugging me. I would require any help I can get.
    Here is the code:
    public class myFileReader{
        void myRecursiveMethod(File dir) {
            File eachFile;
            File[] files = dir.listFiles();
            for (int i = 0;i < files.length; i++) {
                if (files.isDirectory()) {
    if (files[i].list().length > 0) { // I am not sure if this is the right way to go about it. This is one of the ways I tried.
    eachFile = (File)files[i];
    myRecursiveMethod(eachFile);
    System.out.println("Directory: " + eachFile);
    } else if (files[i].isFile()) {
    System.out.println("Files: " + files[i]);
    public static void main(String[]args) throws Exception {
    File dir = new File("C://");
    myFileReader mfr = new myFileReader();
    mfr.myRecursiveMethod(dir);
    Hope to get some responses soon.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    kajbj wrote:
    One line throws the exception, and why aren't you checking what list() returns? It can return null.
    and the whole of this
                  if (files.list().length > 0) { // I am not sure if this is the right way to go about it. This is one of the ways I tried.
    eachFile = (File)files[i];
    myRecursiveMethod(eachFile);
    System.out.println("Directory: " + eachFile);
    } can be replaced by myRecursiveMethod(files[i]);
    System.out.println("Directory: " + files[i]);
    Edited by: sabre150 on May 23, 2009 8:49 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • N-ary Trees non-recursive traversal algorithms

    Hi,
    Non-recursive traversals are needed when you are unsure how big the tree's will be. So far all the algorithms I have seen either use their own internal stack
    or threading to climb back up the tree.
    Here's my attempt that seems to work but I would value so critical evaluation
    * An extension of the CommonAST that records the line and column
    * number.  The idea was taken from <a target="_top"
    * href="http://www.jguru.com/jguru/faq/view.jsp?EID=62654">Java Guru
    * FAQ: How can I include line numbers in automatically generated
    * ASTs?</a>.
    * @author Oliver Burn
    * @author lkuehne
    * @version 1.0
    * @see <a target="_top" href="http://www.antlr.org/">ANTLR Website</a>
    public class DetailAST
        public AST getFirstChild()
        public AST getNextSibling()
        public int getChildCount()
        public DetailAST getParent()
        public int getChildCount(int aType)
        public String getText()
    }This was cut back just to give you enough info
         public static AST getLeftMostChild(DetailAST ast) {
              DetailAST tempAst = ast.getFirstChild();
              while (tempAst.getFirstChild() != null) {
                   tempAst = tempAst.getFirstChild();
              return tempAst;
         public static void traverseASTInOrder(DetailAST root) {
              DetailAST current = getLeftMostChild(ast);
              processNode(current);
              while (current != root) {
                   if (current == current.getParent().getFirstChild()) {
                        processNode(current.getParent());
                   if (current.getNextSibling() != null) {
                        DetailAST sibling = current.getNextSibling();
                        if (sibling.getChildCount() != 0) {
                             current = (DetailAST) getLeftMostChild(sibling);
                             processNode(current);
                        } else {
                             current = sibling;
                             processNode(current);
                   } else {
                        current = current.getParent();
            // do stuff at inorder traversal
         public static void processNode(AST current) {
              System.out.println(current.getText());
         }for pre-order and post-order John Cowan put forward this algorithm
    http://lists.xml.org/archives/xml-dev/199811/msg00050.html
    traverse(Node node) {
        Node currentNode = node;
        while (currentNode != null) {
          visit(currentNode); //pre order
          // Move down to first child
          Node nextNode = currentNode.getFirstChild();
          if (nextNode != null) {
            currentNode = nextNode;
            continue;
          // No child nodes, so walk tree
          while (currentNode != null) {
            revisit(currentNode)     // post order
            // Move to sibling if possible.
            nextNode = currentNode.getNextSibling();
            if (nextNode != null) {
              currentNode = nextNode;
              break;
           // Move up
           if (currentNode = node)
          currentNode = null;
           else
          currentNode = currentNode.getParentNode();
      }Any comments, criticisms or suggestions ?
    regards
    David Scurrah

    Stack is recursion? As far as I know recursion is when
    function (method) calls itself. Just using some
    Collection, which java.util.Stack implements is not
    recursion.
    Regards
    PawelStacks are used to implement recursive algorithms. What happens in most languages when you make a function call? Each function has an "activation record" where it stores its local variables and parameters. This activation record is usually allocated on a stack. Thus for any recursive algorithm, there is a non-recursive algorithm that uses a stack.
    In the OP's case you don't need a stack because of the peculiarities of tree traversal when you have a pointer to the parent node. (Namely, no cycles and you can get back to where you've been) So the algorithms he gave should work fine.
    My only "criticism" would be that it may be more useful to implement these algorithms with the iterator pattern. So you would have a tree with some functions like:
    public class Tree{
        public TreeIterator inOrderIteraror();
        public TreeIterator preOrderIterator();
    }Where the TreeIterator would look like a java.util.Iterator, except maybe you want some additional utility methods in there or something.
    Other than that, non-recursive algorithms are defnitely the way to go.

  • JTree traversal with key events

    I am looking for any classes available for traversing nodes in Jtree based on the input given through keyboard matching with nearest name in the tree being displayed. This is similar to the feature we have in windows explorer where based on the name we type it selects the nearest node in the tree taking into consideration the expanded paths.
    Thank you in anticipation,
    Srikanth

    What exactly you want to do.
    Have a look at my code, this is what I did a while ago. This may a good start for you.
    tree.addKeyListener(new java.awt.event.KeyAdapter() {
             public void keyPressed(KeyEvent e) {
                tree_KeyReleased(e);
        * JTree Key Released Functionality
        * @param e KeyEvent
       private void tree_KeyReleased(KeyEvent e) {
          try {
          MouseEvent me = new MouseEvent(tree, MouseEvent.MOUSE_RELEASED, 0, 0, 0, 0, 0, false);
          int keyCode = e.getKeyCode();
          // Get the Tree Path
          TreePath selPath = tree.getSelectionPath();
          if (keyCode == e.VK_DELETE) { //KeyCode - 127
             removeSelectedNode();
          else if (keyCode == e.VK_ADD) { // Key Code - 107
             tree.expandPath(selPath);
          else if (keyCode == e.VK_SUBTRACT) { // Key Code 109
             tree.collapsePath(selPath);
          else if (keyCode == e.VK_ENTER) {
             tree_mouseReleased(me);
          else {
          } catch (NullPointerException ex) {
          //System.out.println("Null");
       }

  • Newbie Focus Traversal Problem

    I'm trying to do the equivalent of checking the "Tab Stop" checkbox in the MS C++ compiler's dialog layout tool. In other words, I want to go from field to field with the tab key. I've cut and pasted some code from another web site into my code but it doesn't do anything. Is this really the right code? I can't help be think I'm way off base here because it can't possibly be this insanely complex to do the equivalent of checking a checkbox in C++. Can it? What am I doing wrong?
    None of the println statements are ever hit.
    --gary
    import javax.swing.JDialog;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import java.awt.event.ActionEvent;
    import java.awt.Point;
    import java.awt.Dimension;
    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.border.*;
    import java.util.Arrays;
    import java.util.List;
    public class LoginDialog extends JDialog implements ActionListener {
        private boolean cancel = false;
        private boolean loggedIn = false;
        private String postUrl;
        private JButton cancelButton;
        private JButton loginButton;
        private JPanel myPanel;
        private JTextArea taLogin;
        private JPasswordField taPassword;
        private JTextArea taAccount;
        private Border outline;
        private Border margins;
        LoginDialog(JFrame frame) {
            super(frame, "Login to Your Account", true);
            myPanel = new JPanel();
            margins = BorderFactory.createEmptyBorder(15, 15, 15, 15);
            myPanel.setBorder(margins);
            getContentPane().add(myPanel);
            myPanel.setMaximumSize(new Dimension(100,100));
            myPanel.setLayout(new GridLayout(4,2));
            outline = BorderFactory.createLineBorder( Color.black );
            myPanel.add(new JLabel("Account Name:  "));
            taAccount = new JTextArea("",1,16);
            myPanel.add(taAccount);
            taAccount.setBorder(outline);
            myPanel.add(new JLabel("Admin ID:"));
            taLogin = new JTextArea("",1,10);
            myPanel.add(taLogin);
            taLogin.setBorder(outline);
            myPanel.add(new JLabel("Admin Acct Password:"));
            taPassword = new JPasswordField("");
            taPassword.setEchoChar('*');
            taPassword.addActionListener(this);
            myPanel.add(taPassword);
            cancelButton = new JButton("Cancel");
            cancelButton.addActionListener(this);
            cancelButton.setBounds(80, 40, 100, 100);
            myPanel.add(cancelButton);       
            loginButton = new JButton("Login");
            loginButton.addActionListener(this);
            myPanel.add(loginButton);
            final Component order[] =
              new Component[] {taAccount, taLogin, taPassword};
            FocusTraversalPolicy policy = new FocusTraversalPolicy() {
              List list = Arrays.asList(order);
              public Component getFirstComponent(Container focusCycleRoot) {
    System.out.println("returning first object");
                return order[0];
              public Component getLastComponent(Container focusCycleRoot) {
    System.out.println("returning last object");
                return order[order.length-1];
              public Component getComponentAfter(Container focusCycleRoot,
                  Component aComponent) {
                int index = list.indexOf(aComponent);
    System.out.println("returning next object");
                return order[(index + 1) % order.length];
              public Component getComponentBefore(Container focusCycleRoot,
                  Component aComponent) {
                int index = list.indexOf(aComponent);
                return order[(index - 1 + order.length) % order.length];
              public Component getDefaultComponent(Container focusCycleRoot) {
    System.out.println("returning default object");
                return order[0];
            setFocusCycleRoot(true);
            myPanel.setFocusTraversalPolicy(policy);
            pack();
            setLocationRelativeTo(frame);
            setVisible(true);
        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            boolean good = false;
            loggedIn = false;
            if(source==cancelButton) {
                cancel = true;
                setVisible(false);
            } else if (source==loginButton) {
                String account = taAccount.getText();
                String login = taLogin.getText();
                String password = new String(taPassword.getPassword());
                String postData = account+")+("+login+")+("+password;
                try {
                    URL my_url = new URL("http://www.--myURL--.com/logger.php");
                    HttpURLConnection connection =  (HttpURLConnection)my_url.openConnection();
                    connection.setDoOutput(true);
                    connection.setUseCaches (false);
                    connection.setRequestMethod("POST");
                    connection.setFollowRedirects(true);
                    connection.setRequestProperty("Content-Length", ""+postData.length());
                    connection.setRequestProperty("Content-Language", "en-US");
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    DataOutputStream posted = new DataOutputStream (connection.getOutputStream ());
                    posted.writeBytes(postData);
                    posted.flush ();
                    posted.close ();
                    BufferedReader inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    good = false;
                    while ((inputLine = inStream.readLine()) != null) {
                        System.out.println("Server response: "+inputLine);
                        if (inputLine.substring(0,4).equals("url=")) {
                            postUrl = inputLine.substring(4);
                            good = true;
                            cancel = false;
                            loggedIn = true;
                        } else if (inputLine.equals("invalid login")) {
                            good = true; // server did respond, but response was "invalid login"
                            loggedIn = false;
                    inStream.close();
                    if (!good) {
                         JOptionPane.showMessageDialog(null, "Unable to contact server.\nTry again later.", "alert", JOptionPane.ERROR_MESSAGE);
                } catch (MalformedURLException me) {
                    System.out.println("MalformedURLException: " + me);
                    JOptionPane.showMessageDialog(null, "Unable to contact server.\nTry again later.", "alert", JOptionPane.ERROR_MESSAGE);
                } catch (IOException ioe) {
                    System.out.println("IOException: " + ioe);
                    JOptionPane.showMessageDialog(null, "Unable to contact server.\nTry again later.", "alert", JOptionPane.ERROR_MESSAGE);
                if (loggedIn) {
                    setVisible(false);
                } else {
                    JOptionPane.showMessageDialog(null, "Login or password not correct.", "alert", JOptionPane.ERROR_MESSAGE);
        public boolean ifCancel() { return cancel; }
        public boolean ifLoggedIn() { return loggedIn; }
        public String getPostUrl() { return postUrl; }
    }

    an example here
    http://forum.java.sun.com/thread.jspa?threadID=738872
    which changes a GridLayout's traversal from left-right to up-down
    basically you put the components (in the order you want) into a Component[],
    which is used by the FocusTraversalPolicy for next/previous etc.
    note: won't work across FocusCycles - needs additional code for that

  • [SRP527w] NAT Traversal not available in VPN options!!!

    Hi,
    I'm so disappointed to find such a light and incomplete VPN menu on the SRP527w.
    As a Cisco certified network engineer, I'm testing it because my company needs about twenty ADSL+ 3G Backup router, and Cisco seemed to offer the best solution.
    We need to build a VPN over 3G if the ADSL link fails. Unfortunately, 3G acces in France are routed through a wide private network before reaching the Internet. That's not a matter for one of our Zyxel routers, wich include the NAT Traversal (or NAT-T) feature. But with this Cisco, it's impossible to make the traffic go through the VPN.
    Please tell me that this feature will be included in the next firmware release!
    Regards,
    Gaultier

    Thank you for your lightning-fast answer!
    I downloaded the MR3 RC release, and... it works fine! My VPN is established over 3G.
    Thank you for the great job you did improving the capabilities of the SRP520... Hope there are much more useful features like that on your roadmap!
    Regards,
    Gaultier.

Maybe you are looking for

  • PR 1.1 & Social 1.3 update

    Hello, I have an N8 registered on the Orange network in the UK. I have yet to receive OTA updates for Social 1.3 or PR 1.1. Any others on Orange with this situation? Many thanks. Solved! Go to Solution.

  • Problem in executing BDC through interface.

    Hello, We have developed an interface program for creating notifications through BDC in IW21 . Standard notification transaction IW21 has been enhanced with a screen table control for entering certain data.We have recorded the transaction IW21 in SHD

  • W2K8r2 DC not serving clients

    Problem Context: 4 DC's serving the domain (native W2K3), DC01, 2, and 3 are W2K3x32, DC04 is W2K8r2x64 (newly added). All DC's are GC and DNS. DC's all pass DCDiag with no unexplainable errors LDAP query of the DC's in the site shows all 4, with ide

  • How to remove a loaded image on the stage from a symbol containing a button?

    1st the setup: General map is loaded 2. On a click event, an larger image of the region is loaded with the following code (thanks to Joel's demo). On mouseover the name of the county appears and on click a popup (symbol) shows some info. $('<img id="

  • Last access to programs and tables

    Hello, I need to discover the last time some programs and tables were used... We believe that some objects are no longer used and maybe we could delete them. How could I have this kind of historic use of programs and tables ? Eduardo