JTree path question

I have created a program that basically simulates single celled organisms in a random (non graphical) world, and I want to use a JTree to show the family history and allow the user to bring up an organism's stats by clicking on in the the Jtree, but I have a problem. Each organism has a unique ID number (starting at 0) and that's what I want to display on the tree. I have the code working to add the new organisms to the root, but I want them added as a child to the parent (each child has only one parent for these organisms), but I don't know how to do it. I tried using insertNodeInto but since everything after the root is dynamically generated I don't know how to identify the parent correctly (just using the ID doesn't seem to do anything). Do I need to create a method that somehow copies the entire treemodel into a collection and steps through it? I have the organisms in a collection already (an arraylist to be exact), so I could figure out the lineage by stepping through that, but then how do I build a 'selection path' object that will work to tell Java exactly where I want the child to go? Is the selection path just some kind of array, or is it even possible to build a selection path without a user clicking on a tree node? I hope you can figure out what I'm trying to say here and I appreciate any help you can give.

Start by creating a Map that has your organisms as the key and the nodes they are in as the value. Or just let the organism include a reference to the node that contains it. Either of those would allow you to identify the TreeNode that contains a particular organism.

Similar Messages

  • File path question....

    Yet another really simple question from me, as I've been away from DIAdem for too long.
    I have a program which, in part of it, needs the user to select the path that they want a set of a few hundred files to be saved in. I've tried using FileNameGet, but this requires me to select a file in the directory i want to save into to record the path. I just want the user to have to select the folder once.
    I've tried this:
    '===============
    dim newfilepath
    If  (FileNameGet("ANY",,,,,,"Select the directory to save the new files into:") = "IDOk") Then
      newfilepath=FileDlgDir
    else
    End If
    '===============
    Can I select a directory instead of a file?
    Solved!
    Go to Solution.

    Hello Tom!
    Yes, with the PathNameGet() command.
    Matthias
    Matthias Alleweldt
    Project Engineer / Projektingenieur
    Twigeater?  

  • JTree path

    I built a JTree thanks to several DefaultMutableTreeNode, wich were instantiate by:
    new DefaultMutableTreeNode ( MyCategory );
    MyCategory is an object from a class I made by my self (class CategoryNode)
    The snag is, once I have this tree, I retrieve a given CategoryNode, and I must set the selection of my tree so that this CategoryNode is the one that will be selected.
    I do not understand how to do it. I tried with the "setSelectionPath(TreePath path) " method, but I do not know how to built the TreePath. I do not understand how it works.
    Someone can help me ? Someone as an example of this ?
    Thank you very much !
    Sylvain.

    My english as bad as yours:-))
    i'm russian
    Just an example of finding suitable node.
    import javax.swing.*;
    import javax.swing.tree.*;
    class Test extends JFrame
    public Test()
    super("Test");
    DefaultMutableTreeNode root=new DefaultMutableTreeNode("ROOT");
    DefaultMutableTreeNode n1=new DefaultMutableTreeNode("1");
    DefaultMutableTreeNode n2=new DefaultMutableTreeNode("1_1");
    n1.add(n2);
    String category="founded";
    n2=new DefaultMutableTreeNode("1_2");
    n1.add(n2);
    root.add(n1);
    DefaultMutableTreeNode nnnn=new DefaultMutableTreeNode(category);
    n2.add(nnnn);
    n1=new DefaultMutableTreeNode("2");
    root.add(n1);
    JTree tree=new JTree(root);
    DefaultMutableTreeNode node=findNode(root,category);
    tree.setSelectionPath(new TreePath(node.getPath()));
    JScrollPane scroll=new JScrollPane(tree);
    getContentPane().add(scroll);
    setSize(300,300);
    setVisible(true);
    public DefaultMutableTreeNode findNode(DefaultMutableTreeNode localRoot,Object category) {
    DefaultMutableTreeNode resultNode=null;
    if (localRoot.getUserObject().equals(category)) {
    return localRoot;
    int cnt=localRoot.getChildCount();
    for (int i=0; i<cnt; i++) {
    DefaultMutableTreeNode tempNode=findNode((DefaultMutableTreeNode)localRoot.getChildAt(i),category);
    if (tempNode!=null) {
    return tempNode;
    return resultNode;
    public static void main(String a[])
    new Test();
    best regards
    Stas

  • JTree sizing question...

    Hello:
    I have a JTree for which each cell contains a button. I have written a renderer that renders the button, and I realize that I have to do some special stuff to capture a click on the button. My question is unrelated to all of that.
    The problem is that over time, the labels on my buttons change (and may become longer (wider)), but the tree size does not change. In fact, when I update the button label and the tree is re-rendered the rendering of the button gets "chopped off". I've put the tree in a scroll pane, but this doesn't help - the right side of some of the buttons get cut off to the original tree size. I've tried lots of different variations on setPreferredSize, calling repaint, etc, and am not having any luck. I've put together a demonstration of this behavior in a smallish application that I'm posting here, where I create a 2 node tree with buttons that read "Hi", then I change the button labels to "Goodbye" and re-render. You'll see that the button's are cut off about halfway through the button.
    In case its important - I'm running java version 1.5.0_07 on a 32-bit Linux box.
    Any help would be greatly appreciated. Thanks in advance!
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class JTreeQuestion
      public static void main(String [] args)
        JTreeFrame f = new JTreeFrame();
        f.pack();
        f.setLocation(30, 30);
        //Draws buttons with "Hi" (short string)
        f.setVisible(true);
        ButtonNode.updateString("Goodbye");
        //Draws buttons with longer string, buttons get "cut off"
        f.repaint();
    class JTreeFrame extends JFrame
      JTree tree;
      JScrollPane treeView;
      public JTreeFrame()
        super("My Tree");
        DefaultMutableTreeNode root;
        root = new DefaultMutableTreeNode(new ButtonNode());
        root.add(new DefaultMutableTreeNode(new ButtonNode()));
        tree = new JTree(root);
        tree.setCellRenderer(new ButtonNodeRenderer());
        treeView = new JScrollPane(tree);
        add(treeView);
    class ButtonNode
      public static String str = "Hi";
      public static void updateString(String inStr)
      { str = inStr; }
      String getStr()
      { return str; }
    class ButtonNodeRenderer extends DefaultTreeCellRenderer
      public Component getTreeCellRendererComponent(JTree tree,
                              Object value, boolean sel, boolean expanded,
                              boolean leaf, int row, boolean hasFocus)
        Box theBox = new Box(BoxLayout.X_AXIS);
        super.getTreeCellRendererComponent(tree, value, sel, expanded,
                                           leaf, row, hasFocus);
        DefaultMutableTreeNode jtreeNode = (DefaultMutableTreeNode)value;
        theBox.add(new JButton(((ButtonNode)jtreeNode.getUserObject()).getStr()));
        return (theBox);
    }

    For those who are interested. The DefaultTreeModel has a method named nodeChanged() that tells the tree model that a specific node has changed, and the model re-interprets the cell causing its sizse to change as necessary, so that the full button is rendered now.
    Basically what I did was instead of calling repain, I call a method that I wrote that loops through all the tree nodes, indicates they have changed, then repaint's, and it all works out. My trees are relatively small, so this is fine, but if others face the same problem, you'll probably want to selectively indicate which nodes have changed so the tree model doesn't have to do more work than necessary.

  • JTree path selection

    I have a JTree on the left scrollpane and on clicking the value of a node, I display the value in a text field on the right scrollpane. I change the value and set the value in the JTree . I am unable to make the edited tree path selected. The methods provided in the API do not seem to work.

    Don't the JTree.makeVisible( ... ) or JTree.scrollPathToVisible( ... ) methods help?
    kind regards,
    Jos
    Edited by: JosAH on Aug 23, 2009 6:19 PM: typo

  • JTree Path expansion help

    Hi,
    I have made my own jtree to load all the directories in the c drive. I am making a simple windows type browser. I allow users to select a driectory and create a new directory within it. The thing is, once this new directory is created it doesnt show up so i reinitialize the JTree to load all the directories again, and this time the new directory shows up in the directory it was created in. The problem is that before i reinitialize the tree again, i save a treepath for the directory the user is creating a new directory in., but after i reinitialize the tree i need to expand back to that path, i try using expandPath(savedTreePath) but its not working. Any ideas? Code is below.
    private class NewFolderListener implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
                             .getLastSelectedPathComponent();
                   if (selectedNode == null) {
                        System.out.println("New folder not created");
                        return;
                   File temp = (File) selectedNode.getUserObject();
                   String newFolderPath = temp.getAbsolutePath() + "\\" + "New Folder";
                   System.out.println(temp);
                   temp = new File(newFolderPath);
                   temp.mkdir();
                            TreePath tp = new TreePath(selectedNode.getPath);
                   makeTree();
                             tree.expandPath(tp);
    //Reinitialize tree method
    private void makeTree() {
              try {
                   //setLook();
                   tree = new SimpleTree("C:\\");
                   //location.setText("C:\\");
                   splitPane.setLeftComponent(new JScrollPane(tree));
                   tree.addTreeSelectionListener(new TreeSelectionListener() {
                       public void valueChanged(TreeSelectionEvent e) {
                           DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                              tree.getLastSelectedPathComponent();
                           if(node!=null){
                                MyFile mf = (MyFile)node.getUserObject();
                                location.setText(mf.getAbsolutePath());     
                                fselected = mf;
                           makeRightPane();
                   tree.setExpandsSelectedPaths(true);
                   //cp.validate();
              } catch (Exception e) {
         }Anyone have any idea what i am doing wrong?

    Well ive tried using the tree model, calling methods
    such as reload() reload(node) , but none of the
    reloaded the new directory which was created for the
    node.The reload() method is only useful when you have modified existing nodes.
    Use other methods defined in DefaultTreeModel to change tree structure.

  • JTree image question

    I have a question about using images in a JTree.
    I have like 2 parent nodes who both have a lot of child nodes now i know how to get an image for every node but how do i get 1 image for 1 parent with all his children and another image for the other parent with his children.

    It is a programming problem because i dont know how to give echt DefaultMutableTreeNode his own picture. You should think of it like msn when you log in your contacts are in a Tree and your offline contacts have a red icon and online contacts have green one. I need to to the same for my program(chat program). But i can't figure out how but i know how to give alle the DefaultMutableTreeNode's a picture but i cant give individual one's a picture.
    I hope i cleared things up :)

  • JTree#expandRow() Question

    JTree tree;
    //etc...
    1) /** Expand the tree */
    for (int i=0; i<tree.getRowCount(); i++)
         tree.expandRow(i);
    and tree.getRowCount() = 6
    2) /** Expand the tree */
    for (int i=0; i<6; i++)
         tree.expandRow(i);
    My tree has 6 rows, and each row has its own sub-tree hierarchy.
    I wonder why the first case will expand the whole tree, which includes
    the subtrees of each row.
    But in second case, it only expands the first 6 rows in the tree.
    So basically the question is why (1) and (2) have different tree view outputs??

    Well, after you expand row 1, the row count isn't 6 anymore, is it? It's something larger than that, depending on how many children the first node has.

  • JTree Updating question

    Hi there. I have two questions.
    I have a data structure that is being displayed in a JTree, so I made a Model and it works great. The data structure can be updated from non-gui interaction. The nodes don't change position or anything, its just the data that is displayed is changed. I handle it currently by calling a function in the model I made called nodesChanged(), which basically does the following:
    public void nodesChanged()
        int len = treeModelListeners.size();
        TreeModelEvent e = new TreeModelEvent(this, new Object[] {rootItem});
        for (int i = 0; i < len; i++) {
          ( (TreeModelListener) treeModelListeners.elementAt(i)).treeNodesChanged(e);
      }It does actually work, the changes are reflected in the JTree, but it seems a little expensive, and the updates to the actual data model could come at about 150 per second. To deal with that now, I just use a timer class that updates it about every 3/10's of a second, which does a pretty good job, but is there a more elegant way to do this? Something where the node is an observer of the data in the data structure (which are Observable objects)?
    The second question I have is when I do the above, sometimes the display name of the node will be larger than the value it had previously, but the Textbox (if that's what it is) doesn't grow, so I get a ... at the end.
    For example, if I have "Run" and it changes to "Stopped", it will show up as "Sto...".
    Any help would be great. TIA.

    well, you can start by making the node you put in the tree model event the lowest node in the tree that needs updating, instead of root.
    I don't know about the timer thing, cuz as far as I know, the listener will invoke code that will refresh the renderers, as opposed to painting where repaint calls can be merged into one. If you aren't getting that many updates all the time, you could implement something where the listener fires to an intermediate listener which will fire the info to the tree after a slight delay. That way if you get multiple updates, you can effectively ignore lots of them.
    The ... thing, I thought that treeNodesChanged was the appropriate method, although maybe it has to be for the specific node, not root.

  • Path question

    Hi,
    I have two questions about paths
    1. After making a stoke on a path, I made some adjustments on the path. But it doesnt affect the sroke. Is thre a way to do this.
    2. Is there a way of deforming a layer by a curve.
    Thank you.

    you can still use Warp, just not the manual warp, select Arc or something like that from the Options bar. If you're pipe is vertical then you could also try your luck with Filter->Distort->Shear but i'd say that this too is more Illustrator territory
    edited

  • How to get the JTree path including the rest of its node

    I want to listen for expansion and collapse events in a JTree including the rest of all its children and nodes. Because if the tree have some similar or same nodes at the upper level, it is hard to know which node has been selected. That is why I want to know all its children.
    I think the traditional way can not be implemented.
    JTree tree = (JTree)evt.getSource();
    TreePath path = evt.getPath();
    Does someone has any idea?
    Thank you.

    My code below turns the selected node in a tree into a Complete Window's Style Path:
        //Get the Path
        TreePath path = tree.getSelectionPath();
        String address;
        if (path == null) return;
        address = new String();
        //Convert Path to String: format is [ root , subtree1, node2, child 3] etc
        address = path.toString();
        //Lop first bit off leaving root, subtree1, node2, child 3]
        address = address.substring(1);
        //Convert ", " into "\" character to make root\subtree1\node2\child 3]
        //replaceAll method uses regular expressions - hense \\\\ only equals one
        ///after being processed..
        address = address.replaceAll(", ","\\\\");
        //remove trailing ]
        address = address.replace(']','\\');This may be what your looking for, or alternatively, it may not.
    Hope it helps set you in the right direction.
    Phillip Taylor
    www.geocities.com/PhillipRossTaylor/

  • How to activate mouse right click  on a JTree PATH

    Hi,
    I'm trying to generate a pop menu in a Jtree on mouse event right click.
    So far it is okay, but the problem I have now is to popup the menu only if a precise element of the Jtree is selected.
    Here is some pieces of my code :
    private void fill_panelCenter() {
    stmt.init(conn.getconn());
    ttree.build_root(racine, stmt.getTables(), stmt.getViews(), stmt.getIndexes(), stmt.getPackages(), stmt.getProcedures(), stmt.getFunctions());
    NewTree = new JTree(ttree.getracine());
    NewTree.setBounds(new Rectangle(0, 0, 288, 677));
    trexTree.setVisible(false);
    NewTree.setVisible(true);
    NewTree.addTreeSelectionListener(new TreeSelectionListener(){
    public void valueChanged(TreeSelectionEvent e)
    popup.add("Edit");
    NewTree.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    NewTree_mouseClicked(e);
    jScrollPane1.getViewport().add(NewTree, null);
    panelCenter.add(jScrollPane1, null);
    private void NewTree_mouseClicked(MouseEvent e) {
    if (e.get && e.getButton() == 3) {
    popup.show(e.getComponent(), e.getX(), e.getY());
    }

    Hi,
    Thanks for tip, well i didn't use exactly what was there but it help me
    make my own.
    And i find it a bit more simple so for anybody who that might help :
    NewTree.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (e.getButton() == 3) {
    TreePath path = NewTree.getPathForLocation(e.getX(), e.getY());
    if (path != null) {
    popup.show(NewTree, e.getX(), e.getY());
    Remember to replace NewTree by your own !
    :-D
    Well well I just need to make the path selected now .... I mean after the right click so the user knows which path he has selected.
    Any ideas ?

  • Interleaving to Fast Path Question

    Hi,
    After recently getting my broadband line issues sorted, I am still experiencing consistant Lag issues while online Gaming on Xbox live.
    After reading up at great length on the internet about other peoples issues, it seems that Interleaving is a main factor in playing Call of Duty Games especially. My question is though would I be able to switch to fast path?
    My router/modem stats are:
    ADSL Line Status
    Connection information
    Line state:
    Connected
    Connection time:
    3 days, 05:08:45
    Downstream:
    2,816 Kbps
    Upstream:
    448 Kbps
      ADSL settings
    VPI/VCI:
    0/38
    Type:
    PPPoA
    Modulation:
    G.992.1 Annex A
    Latency type:
    Interleaved
    Noise margin (Down/Up):
    5.6 dB / 15.0 dB
    Line attenuation (Down/Up):
    56.0 dB / 31.5 dB
    Output power (Down/Up):
    18.7 dBm / 11.9 dBm
    FEC Events (Down/Up):
    1313806 / 182
    CRC Events (Down/Up):
    2872 / 100
    Loss of Framing (Local/Remote):
    0 / 0
    Loss of Signal (Local/Remote):
    0 / 0
    Loss of Power (Local/Remote):
    0 / 0
    Loss of Link (Remote):
    0
    HEC Errors (Down/Up):
    17536 / 87
    Error Seconds (Local/Remote):
    0 / 0
    Solved!
    Go to Solution.

    that is showing that interleaving is working personally unless you really must have interleaving turned off i would leave it on as it improves stability going to fast path could make your line unstable if you want to go to fast path you need to contact the forum mods this is a link to them and ask them to turn off interleaving
    http://bt.custhelp.com/app/contact_email/c/4951
    they normally reply by email or phone directly to you within 3 working days
    They are a UK based BT specialist team who have a good record at getting problems solved
    If you want to say thanks for a helpful answer,please click on the Ratings star on the left-hand side If the reply answers your question then please mark as ’Mark as Accepted Solution’

  • Path question in Illustrator CS4

    Hi...I am impoorting a bar graph from Microsfot Excel to Illustrator CS4. So far, so good. I can simply cut and paste from the clipboard and Illustrator understands the Excel graph. What I want to do is to convert the graph to grayscle (which I've done), then apply a spot color to just one of the bars in the graph. I'm able to use the direct selection tool to select one of the bars. Each bar appears to be its own path. Then I open up the swatches menu and apply a color. But ALL of the bars in the graph turn that color, as if all of the paths are the same. Is there any way to ungroup a path? I tried the "ungroup" command to no avail. Thanks.

    Thanks, Kurt. I figured out how to do it. Actually, I figured out two different ways:
    1. Using OBJECT/COMPOUND PATH/RELEASE
    and
    2. WINDOWS/PATHFINDER/DIVIDE
    Both seem to work.

  • [CS5-JS] Link path question

    Hi,
    I made a script that needs the path of every link within the document.
    I tested it on a Mac (10.5.8) and when I look at links path (document.link.filePath) I see strings like these:
    Username:Desktop:WorkFolder:myFile.jpg
    It looks like paths starts from the user folder.
    I thought it was due to the fact that this user is not an administrator.
    So I tested the same script on another computer (10.6.4) but the path looks correct:
    MacintoshHD:Users:Username:Desktop:WorkFolder:myFile.jpg
    Obviously I have some problems while passing this value because in the first case it doesn't point to afile object...
    Is it a OS issue?
    I don't know how to solve it...
    Thanks!

    Hi
    I think you should use ObjectStyle!
    create an Object Style and set some transparency settings, and apply this to objects
    var my_obj_style;
    try { 
      my_obj_style = myDoc.objectStyles.add({name:"inner glow setting"});
    catch(e){
      my_obj_style = myDoc.objectStyles.item("inner glow setting");
    with (my_obj_style.transparencySettings.innerGlowSettings){
      applied = true;
      blendMode = 1852797549/*BlendMode.NORMAL*/;
      opacity = 100;
      noise = 0;
      effectColor = "Paper";
      technique = 2020618338/*GlowTechnique.PRECISE*/;
      spread = 79;
      size = '0.125in';
      source = 2020618594 /*InnerGlowSource.EDGE_SOURCED*/; 
    //Create the ovals and specify their size and location...
    var myLeftOval = myPage.ovals.add({geometricBounds:[2, -3, 2.75, -.75], fillColor:myDoc.colors.item("25% Black"),strokeColor:myDoc.swatches.item("None"), itemLayer:myDoc.layers.item("New Layer"),appliedObjectStyle:my_obj_style});
    var myCenterOval = myPage.ovals.add({geometricBounds:[3, -3, 3.75, -.75], fillColor:myDoc.colors.item("25% Black"),strokeColor:myDoc.swatches.item("None"), itemLayer:myDoc.layers.item("New Layer")});
    var myRightOval = myPage.ovals.add({geometricBounds:[4, -3, 4.75, -.75], fillColor:myDoc.colors.item("25% Black"),strokeColor:myDoc.swatches.item("None"), itemLayer:myDoc.layers.item("New Layer"),appliedObjectStyle:my_obj_style});
    I didn't apply object style to center oval, on purpose.
    Thankyou
    mg.

Maybe you are looking for

  • Error 1003 At Open VI Reference

    I'm calling a VI from a library using the Open VI Reference. The main program in an executable file. If I make a change to the *.llb and try to call it using the main program I get an error 1003 Open VI Reference is not executable. Now I've made chan

  • Application, once built, shows "Not Responding" in the toolbar, and it doesn't go away

    If you have an application that is running with some kind of timeout, (My application will send a message, and wait for a user definable period of time for a reply). If this tine is over 5 seconds, and the user clicks on the application, the app sets

  • Making "Go to a Page View" the Default Link Action

    Up until recently, it was quick and easy for me to add a "Go to a Page View" link to PDFs in Acrobat Pro. I highlighted the text I wanted to link, right-clicked on it, and then selected Create Link from the pop-up menu. At that point, the Create Link

  • Did OS 10.9.1 gum up internet speed?

    Computer at work (Verizon is ISP, DSL) and another 2 machines at home (cable isp), both Firefox and Safari are incredibly slow even though Speedcheck seems OK (6600 at work and 15,500 at home!).  Gummed up since OS 10.9.1 update after noon today.  Oh

  • Hard Drive Icon (Macintosh HD) Disappeared - How do I get it back

    Hi, My Macintosh HD Icon that has been at the top right of my desktop forever is gone. Anyone know how to restore it? Getting to the hard drive now is a pain. Thanks.