Refresh JTree keep node x-y position

Hi,
I have a JTree which is the folders of the file system. Over time, new folders added/deleted before/after a selected node, so I need to refresh it. How to keep the selected node at the same x-y location of the view?
I can keep the selected node in the view (visible), but the x-y position may change.
Any information would be appreciated. Thanks in advance.

Without seeing any code, tha best I can offer is
-- before refreshing, store the visible rectangle and the location of the selected node
-- after refreshing, obtain the location of the selected node and compute the offset
-- compute the new desired visible rectangle and scrollRectToVisible
To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
db

Similar Messages

  • Problem in refreshing JTree inside Jscrollpane on Button click

    hi sir,
    i have problem in refreshing JTree on Button click inside JscrollPane
    Actually I am removing scrollPane from panel and then again creating tree inside scrollpane and adding it to Jpanel but the tree is not shown inside scrollpane. here is the dummy code.
    please help me.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class Test
    public static void main(String[] args)
         JFrame jf=new TestTreeRefresh();
         jf.addWindowListener( new
         WindowAdapter()
         public void windowClosing(WindowEvent e )
         System.exit(0);
         jf.setVisible(true);
    class TestTreeRefresh extends JFrame
         DefaultMutableTreeNode top;
    JTree tree;
         JScrollPane treeView;
         JPanel jp=new JPanel();
         JButton jb= new JButton("Refresh");
    TestTreeRefresh()
    setTitle("TestTree");
    setSize(500,500);
    getContentPane().setLayout(null);
    jp.setBounds(new Rectangle(1,1,490,490));
    jp.setLayout(null);
    top =new DefaultMutableTreeNode("The Java Series");
    createNodes(top);
    tree = new JTree(top);
    treeView = new JScrollPane(tree);
    treeView.setBounds(new Rectangle(50,50,200,200));
    jb.setBounds(new Rectangle(50,300,100,50));
    jb.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
              jp.remove(treeView);
              top =new DefaultMutableTreeNode("The Java ");
    createNodes(top);
              tree = new JTree(top);
                   treeView = new JScrollPane(tree);
                   treeView.setBounds(new Rectangle(50,50,200,200));
                   jp.add(treeView);     
                   jp.repaint();     
    jp.add(jb);     
    jp.add(treeView);
    getContentPane().add(jp);
    private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode book = null;
    category = new DefaultMutableTreeNode("Books for Java Programmers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Tutorial Continued: The Rest of the JDK");
    category.add(book);
    book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs");
    category.add(book);
    book = new DefaultMutableTreeNode("Effective Java Programming Language Guide");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Programming Language");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Developers Almanac");
    category.add(book);
    category = new DefaultMutableTreeNode("Books for Java Implementers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Virtual Machine Specification");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Language Specification");
    category.add(book);
    }

    hi sir ,
    thaks for u'r suggession.Its working fine but the
    properties of the previous tree were not working
    after setModel() property .like action at leaf node
    is not working,I'm sorry but I don't understand. I think you are saying that the problem is solved but I can read it to mean that you still have a problem.
    If you still have a problem then please post some code (using the [code] tags of course).

  • JTree delete node

    Have a problem with JTree
    A node I call folderNode will normally contain sub-nodes with names lik subnode1,subnode2,subnode3 etc. (Just examples)
    The folder node will then represent the range, so for one with the mentioned subnodes, name would be "subnode1- subnode3".
    To update this foldername after I have deleted say nr 3, I use "theFolderNode.setUserObject("new name here")), and then treeModel.nodeChanged(theFolderNode); I would then expect "subnode1- subnode2". (Don't mind the method of finding the correct label..)
    If I then try to get the new userObject and checking by typing:
    System.out.println(theFolderNode.getUserObject().toString()); - I actually get out what I want, but the label of the FolderNode is still not updated..
    What am I missing here??

    Here is an excert from an article from javaworld
    "The Java programmer must keep in mind that it is the garbage collector that runs finalizers on objects. Because it is not generally possible to predict exactly when unreferenced objects will be garbage collected, it is not possible to predict when object finalizers will be run. Java programmers, therefore, should avoid writing code for which program correctness depends upon the timely finalization of objects. For example, if a finalizer of an unreferenced object releases a resource that is needed again later by the program, the resource will not be made available until after the garbage collector has run the object finalizer. If the program needs the resource before the garbage collector has gotten around to finalizing the unreferenced object, the program is out of luck."
    http://www.javaworld.com/javaworld/jw-08-1996/jw-08-gc.html
    Generally without any tweaking the GC only runs when it has to, so your memory with be recycled then.
    You can call System.gc() but that doesn't cause garbage recycling, but rather tells the JVM that you would like to do it, and then it will do it sometime after that.

  • Tree control's nodes and ites position

    Hello,
    Is there a way to get tree's nodes and items position,or
    get it by ElementVisualizationMode and Hit event ?
    Thanks,
    Assaf

    Hi
    Using the new features, and I think I have found a bug that I was wondering if anyone else can comment on.
    GetNodeLeft(BSTR key) ... perfect
    GetNodeTop(BSTR Key) ... perfect
    GetNodeHeight(BSTR Key) ... perfect
    BUT
    GetNodeWidth(BSTR Key) ... returns weird values, except for the first item in the tree.
    The function then returns what seems to be:
    (Control Width - (Height * Absolute Position))
    The deeper one goes into the tree, the smaller the width becomes ...
    Surely this is a bug ....

  • Align layer A to B, but keep layer B's position locked?

    In Illustrator, you can center a number of objects, but keep one stationary -- all the objects center to it.
    Is there a way to center two layers, but keep one of their positions locked?  Locking a layer prevents it from being a selected.

    http://aescripts.com/alignlayers/
    found with this search

  • Refresh icon keeps on moving  on expanding  year refinement.

    Hi All,
    Year refinement was coming as 2,006.00 because in metadata we took it as number.since it was year name I changed it to string and ran initial load but  now year refinement is not displaying anything.The refresh icon of endeca keeps on rotating on clicking year.Does anyone know why refresh icon keeps on moving  on expanding  year refinement.
    Thanks and Regards,
    Amrit

    Advice from a fellow lefty:
    I rarely use the toolbar icons. To much movement. Command key shortcuts are the way to go.
    For refresh: use Command/R keys.
    Move to the Address Window Command/L
    Search window command/option/F
    Bookmarks Manager Command/Option/B
    and on it goes....

  • Remove background in JTree's node

    How to remove colored background in JTree's node?
    http://www.builder.cz/images/client-tree.gif - here is example how it looks like...

    from reading understand white would be best...
    You may have misunderstood.
    In the image you posted there seems to be a problem with a part that strongly reflects the background for example.
    The »ideal« color for efficient clipping depends on the object being photographed, even a green screen would be problematic with an object of a similar green.
    What is the file format you need anyway? psd with transparency or eps with Clipping Path or …?
    Like Silkrooster pointed out Actions and Image Processor, but also Scripts, can help with automising the task with Photoshop – but quite frankly I expect results so bad that each image would likely have to be checked and improved manually.

  • Adding nodes to specific positions of JTree

    Hi guys, I have a JTree that basically represents a file explorer with all the folders and files in a drive. I want to automatically refresh the tree if there are any new files added to that drive. What my idea was to:
    1. Set a timer to check the list of files in that directory every 1 second
    2. If there are any changes, I would obtain the path of the file
    3. Create a new DefaultMutableTreeNode for that file
    4. Add this node into the JTree.
    The problem I have right now is that all the debug checks are printing the right stuffs. However, JTree doesn't add the new node if files are placed in a sub folder, or a folder is copied into the directory. The code is not ready to detect file deletion yet.
    Here is my code:
    public static void refresh(final File dir, final JTree fileTree)
         //Start the timer
         final Timer timer = new Timer(1000, new ActionListener()
              //Get a list of the files
              List<File> listA = new ArrayList<File>(listAllFiles(null, dir, 2));
              public void actionPerformed(ActionEvent ae)
                   int c = 0;
                   List<File> listB = new ArrayList<File>(listAllFiles(null, dir, 2));
                   //Files added
                   if (listA.size() < listB.size())
                        File[] files = new File[listB.size() - listA.size()];
                        //Find out which file is it
                        for (int i = 0; i < listB.size(); i++)
                             //File found
                             if (!listA.contains(listB.get(i)))
                                  //Get all the new files into an array
                                  files[c] = (File) listB.get(i);
                                  c++;
                        //Update the list first
                        listA = listB;
                        //Update each file into the file tree
                        for (int i = 0; i < files.length; i++)
                             //Remove user.dir path
                             String filePath = files.getAbsolutePath();
                             String userDir = System.getProperty("user.dir");
                             filePath = filePath.substring(userDir.length() + 1, filePath.length());
                             //Convert path separator to / for splitting
                             if (System.getProperty("os.name").contains("Windows"))
                                  filePath = filePath.replaceAll("\\\\", "/");
                             //Convert it to tree path
                             Object root = ((DefaultTreeModel)fileTree.getModel()).getRoot();
                             String str[] = filePath.split("/");
                             Object obj[] = new Object[str.length];
                             obj[0] = root;
                             for (int j = 0; j < str.length - 1; j++)
                                  obj[j + 1] = new DefaultMutableTreeNode(str[j]);
                             TreePath path = new TreePath(obj);
                             //New node to be added into the fileTree
                             DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(files[i].getName());
                             DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                             ((DefaultTreeModel)fileTree.getModel()).insertNodeInto(newNode, parentNode, parentNode.getChildCount());
         timer.start();

    bumps..

  • JTree doesn't refresh when adding node in a node

    Hello,
    I have a strange problem
    I have a JTree, with a root, and two nodes, which have nodes...
    I have one node that is expanded, and the other is collapsed.
    I made a method that enables me to add a sub node to the node selected by the mouse.
    If I select the collapsed node and use my "add" method, and then expand the node, the node is here. No problem.
    If I do the same thing on the expanded node, the tree doesn't seem to be willing to refresh. I can use some refresh(), expandPath()...and other methods to make it refreshed, but it doesn't care... is there some particular method that I must use, a listener that I must add to the tree....?
    Any help would be appreciated
    Thanks 4 help
    Philippe

    You need to call nodeStructureChanged(parentNode) on the model.

  • How to Refresh JTree if a file System got changed during Run-time

    Hi,
    Can anyone tell me how to refresh a JTree(javax.swing.JTree) used for displaying file system(both local and remote).
    I'm getting a problem if a file/directoy is added to the file system, after my Applet is loaded. Actually, i have used DefaultTreeModel's reload() method for refreshing and calling it inside SwingUtilities.invokeLater() using Thread, but its not working.
    I want that the tree should reflect the latest Files/Directories on the click of a node, if any file or directory is added under that node.
    Plz tell me if this is possible or not.
    Thanks

    Hi Shay_te,
    Thanx for ur reply as i was eagerly waiting for the one.
    but the example is using the TreeTable
    and i have used JTree and DefaultTreeModel.
    I'm calling reload(node) within treeExpand() method
    Then, i'm regestring addTreeModelListener() as
    m_model.addTreeModelListener(new javax.swing.event. TreeModelListener(){ }
    inside which all 4 methods are over-ridden
    code snippet is as follows so plz help me and tell if this the right way:
    class DirExpansionListener implements TreeExpansionListener{
            DirExpansionListener(){
            public void treeExpanded(TreeExpansionEvent event) {
                final DefaultMutableTreeNode node = getTreeNode(event.getPath());
                final FileNode fnode = getFileNode(node);
                Thread runner = new Thread() {
                    public void run() {
                        if (fnode != null && fnode.expand(node)) {
                            Runnable runnable = new Runnable() {
                                public void run() {
                                    try{
                                       m_model.reload(node);
                                        m_model.addTreeModelListener(new javax.swing.event.TreeModelListener() {
                                            public void treeNodesChanged(javax.swing.event.TreeModelEvent evt) {
                                            public void treeStructureChanged(javax.swing.event.TreeModelEvent evt) {
                                                System.out.println("Path of node changed->"+evt.getTreePath());
                                            public void treeNodesInserted(javax.swing.event.TreeModelEvent evt) {
                                                System.out.println("Nodes Inserted method called..");
                                            public void treeNodesRemoved(javax.swing.event.TreeModelEvent evt) {
                                        System.out.println("Run inside DEvent called..");
                                        //Thread.sleep(500);
                                        //fnode.expand(node);
                                    }catch(Exception e){System.out.println("err :" +e);}
                            SwingUtilities.invokeLater(runnable);
                runner.start();
            public void treeCollapsed(TreeExpansionEvent event) {}
        Please reply...

  • Refreshing JTree with a customized TreeModel

    Hello,
    I'm newer to Swing, and I'm seeking for help for a JTree problem.
    I hoped to display an XML document with JTree. So I customized a TreeModel and TreeNode to handle the XML data.
    I used DOM to handle XML, and define TreeNode with the following class:
    class DOMtoTreeNode {
    org.w3c.dom.Node domNode;
    public DOMtoTreeNode(org.w3c.dom.Node myNode){
    this.domNode = myNOde; }
    public String toString() {
    //the displaying code
    //and other necessary code to handle children of domNode
    Then I defined an implementation of the TreeModel Interface.
    public class DomTreeModel implements javax.swing.tree.TreeModel
    Document document;
    public DomTreeModel(Document aDomDoc){   
         this.document = aDomDoc;
    // Basic TreeModel operations
    I didn't define any personal TreeModelListener for this TreeModel
    and then I created a JTree object to display the XML tree
    treeModel = new DomTreeModel(someDOMDocument);
    treeInputParameter = new JTree( treeModel );
    and I defined JtreeListener.
    What I hoped to do is to make modification for the XML document in the JTree.
    I added the editing functions in the "valueChanged" function. I added a new DOM node as a child of an existing element node by directly append the child in the DOM node. The code is like the follows:
    DOMToTreeNode treeNodeSelected =(DOMToTreeNode)
    treeInputParameter.getLastSelectedPathComponent();
    org.w3c.dom.Node domNode = treeNodeSelected.getNode();
    //get the dom node from Jtree Node here
    domNode.appendChild(someChildDomNode);
    Up to now, it seems work fine. The TreeModel updates the DOM Document, and the modification being shown in JTree.
    But when I tried to replace an existing node with a new node, something went wrong.
    domNode.replace(newChild, oldChild);
    I debugged the code, and found the underlying DOM Document in the TreeModel had been successfully changed, but the TreeModel didn't update the display in JTree.
    I'm afraid this is quite a naive question, but would someone be kindly help me deal with this? It seems that the reason is that some code is missing to let the TreeModel refresh the frontend JTree display. But I realy don't know how to tackle this.
    Thanks!
    Haoxiang Xia

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

  • Soundtrack Pro Won't Refresh And Keeps Crashing!

    Hi,
    Got a lot of issues with Soundtrack Pro, so much so that I've been using the basic Soundtrack version rather than the upgrade.
    I'm using a G4 with FCP HD and the biggest problem I have with Soundtrack Pro is that it just keeps crashing!! I've also found that trying to use the Graphic Equalizer function crashes everything, from Sountrack Pro, Soundtrack, right through to Final Cut. Every other audio filter works fine in Final Cut, except for the EQ filter. But lots of functions inside Soundtrack Pro, crash it.
    I can only use it for short clips and short periods of times . But the worst thing is, if I save a clip either from Final Cut or from Soundtrack Pro itself, the moment I try and open that new clip, it doesn't appear in the browser. I have to close the software down, open it and THEN it appears in the browser. I can't find anyway of refreshing the file list.
    Strangely this 'saved files not appearing' problem also happens in DVDSP, as well as Soundtrack Pro, but it never happens in Final Cut HD. Any solutions?

    "is there anything unusual about the location where you save these files? (on a network volume, or something)"
    I don't think so, although my boot drive was formatted separately from my video drive, they are both internal. But it doesn't matter if I save the file on the video drive or the boot drive, STP won't see them until I shut the program down and reopen it again.

  • Why can't I log in to my iTunes account (iPod Touch)? Whenever I put in the password it refreshes and keeps prompting me - it doesn't say it is incorrect, it just refreshes it.

    I just bought an iTunes card and was eager to redeem it. My iPod prompted me to log in as usual, but when I put in the correct password it just kept prompting me again. I've tried putting in my password to log in but it won't allow me to get into my account, rather it just refreshes and prompts me, and I've been doing this about ten times before I gave up. My internet connection is fine and all else is running smoothly.
    And no, it isn't the incorrect password. I have tried putting in an alternative password to check, before refreshing it said it was incorrect.
    With the correct password it'll just keep prompting me over and over so I cannot get in. This is really annoying and I don't know what to do as this hasn't happened before.
    If anyone knows what is going on please inform me.
    (Also: I cannot sync my iPod into any computers at the moment. I lost the previous computer and if I synced it with the new one I would lose everything on it, and some information on there is dear to me such as photos and videos. That is if I had a choice - computers with iTunes don't seem to recognise it as an iPod device, rather a camera which I can't take anything off of.
    This is another problem on its own, though.)

    Have you tried going to Settings>iTunes and App Stores (or just Store) and signing out and then signing in again?

  • Jtree custom nodes

    Hi there,
    the "How to Use Trees" tutorial shows how to create simple JTrees where each node is a String:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    I need to have tree structure where each node is like a form entry.
    For example some like this:
    + name: [ ........... ]
    + surname: [ ........... ]
    + child
    ---------+ name: [ ........... ]
    ---------+ surname: [ ........... ]
    and so on...
    The best way that I can think of to do that is to make each node be a JPanel and add to it a JLabel and a JTextField. If this is really the best way to do that then my JTree needs to have something different than DefaultMutableTreeNode as nodes because they can only be used to display Strings.
    So provided there is no better way to do what I want to do, the question is, how do I put a JPanel in a JTree node?

    I think the better way is to use a UserObject giving a summary String in its toString method for standard node display, and to display an extra JDialog for editing all the details of the UserObject if the user chooses to edit the node. Imho, displaying complex nodes directly in the tree tends to confuse the user.

  • JTree multiple nodes selection problem !

    I can not make my JTree to be in multiple node selection mode.
    I have custom tree model and tree node class, the tree model class
    implements javax.swing.tree.TreeModel, and the tree node is an ordinary
    Java object.
    In this setting, my JTree is always in single selection mode.
    I have tried set the selection model after the JTree has initialized, and
    it didn't work.
    What I missed in TreeModel implementation ? Or should my tree node class
    also implements javax.swing.tree.TreeNode ?
    Don't tell me just call
    xxtree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    It didn't work.

    Just in case anyone wants to know, I did find the magic number of files, and what the problem is. I talked with tech suppot at Adobe, and they know the problem exists, but won't fix it. I did put in a request in the "Request a Feature" form. Read on:
    The magic number is 40 Canon 1Ds Mark III Raw files, and clicking on three or more keywords. The key to not having the numbers of keywords counted incorrectly in the filter pane is to click on the keywords as fast as you can before it starts to write to the metadata. If you click on each keyword one at a time, and wait about a second or more between selecting the keywords, then the counts in the filter panel for the number of keywords is not correct in relation to the number of files that you have chosen to apply keywords to. The cure for this is to click as many keywords as possible as fast as you can before the software starts incorporating the keywords into the metadata.
    I would suggest to Adobe, that a nice feature would be that one could click on as many keywords as one would want, to as many files one would want, and then have a button or icon that would enable one to then apply all the keywords at once, instead of applying them as you click them as it is now. I also would love it if Adobe fixed it now instead of waiting to fix it in the version of CS5. Someone on Adobe's support line told me that Adobe would rather wait to put this into the CS5 version than fix it now. I don't think that is right, but heck, I am only one guy who depends on this software to provide images keyworded to my clients in a timely manner. I would never run my business like this Adobe. If there is a problem, and there is, please fix it now, or give me some of my money back since your product has a design flaw that is having a negative impact in my ability to to my job and run my business.
    Thanks!
    Daniel Root
    Portland, OR

Maybe you are looking for