Solved

Adding nodes to a JTree and refreshing

Posted on 1999-01-28
15
705 Views
Last Modified: 2008-02-20
I have an application with a JTree component,

however, the Jtree model is set from an adapter which creates the nodes from a database.

Now my problem is how can i get the Jtree to refresh itself if the info in the database changes, i.e. more nodes added?

What i am currently doing is creating a new instance of the model, as reload has no effect. If i do reload and also refresh the info in the adpater the Jtree does not recognise that nodes have been added and thus not reflected on the JTree component,

can anyone help?
0
Comment
Question by:plaskowj
  • 8
  • 5
  • 2
15 Comments
 
LVL 8

Expert Comment

by:diakov
ID: 1234829
have you tried revalidate() of the jtree?
0
 

Author Comment

by:plaskowj
ID: 1234830
what does revalidate actaully do?
0
 
LVL 8

Expert Comment

by:diakov
ID: 1234831
"

Support for deferred automatic layout.

Calls invalidate() and then adds this components validateRoot to a list of components that need to be validated. Validation will occur after all currently pending events have been dispatched. In other words after this method is called, the first validateRoot (if any) found when walking up the containment hierarchy of this component will be validated. By default, JRootPane, JScrollPane, and JTextField return true from isValidateRoot().

This method will automatically be called on this component when a property value changes such that size, location, or internal layout of this component has been affected. This automatic updating differs from the AWT because programs generally no longer need to invoke validate() to get the contents of the GUI to update.

See Also:

Component.invalidate(), Container.validate(), isValidateRoot(), RepaintManager.addInvalidComponent(javax.swing.JComponent)

"


0
 

Author Comment

by:plaskowj
ID: 1234832
Ok so here we go

I have created a adapter for the model
inside this adpater i reload the information(method called refreshme so my refresh method the tree looks like this

RefreshTree(){
 data.refreshMe();//here as the db is updated new nodes are added
 tree.revalidate();
}  

//but nothing happens
0
 
LVL 16

Accepted Solution

by:
heyhey_ earned 10 total points
ID: 1234833
diakov:
'don't mislead the man' :))

this is a classic model-view situation.
when model detects some changes in the data, it should inform the view.
In Swing this functionality is implemented during standard EventSource -> EventListener pattern.

DefaultTreeModel has the appropriate helper methods
 fireTreeNodesChanged
 fireTreeNodesInserted
 fireTreeNodesRemoved

if you implement your own TreeModel, you should handle all the Listener regiostering and notification yourself ..
 addTreeModelListener(TreeModelListener)
 removeTreeModelListener(TreeModelListener)

and when your model detect changes, it should call the appropriate method on all the registered listeners
 treeNodesChanged(TreeModelEvent)

Invoked after a node (or a set of siblings) has changed in some way.
 treeNodesChanged(TreeModelEvent)
 treeNodesInserted(TreeModelEvent)
 treeNodesRemoved(TreeModelEvent)
 treeStructureChanged(TreeModelEvent)

best regards
  heyhey
0
 

Author Comment

by:plaskowj
ID: 1234834
excellent, do you an example of this

many thanks
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1234835
if you need more informatin, you can take a look at the source of
DefaultTreeModel to see how inserting / removing nodes is implemented (DefaultTreeModel fires the appropriate event to all its listeners on such a change)
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:plaskowj
ID: 1234836
I have added the action listeners to my model (newModel)
i.e.

 newModel.addTreeModelListener(new com.sun.java.swing.event.TreeModelListener() {
      public void treeNodesChanged(TreeModelEvent e) {
      }
      public void treeNodesInserted(TreeModelEvent e) {
        newModel_treeNodesInserted(e);
      }
      public void treeNodesRemoved(TreeModelEvent e) {
      }
      public void treeStructureChanged(TreeModelEvent e) {
      }
    });

but how for examples do i get the newModel_treeNodesInserted(e)
method to load up the new code, taking into account thye nodes are made up of database records

can you help, please
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1234837
no.

you need to implement these two methods in your TreeModel to handle registering of TreeModel listeners (TreeModelUI is one og them)

    public void addTreeModelListener(TreeModelListener l) {
        listenerList.add(TreeModelListener.class, l);
    }

    public void removeTreeModelListener(TreeModelListener l) {
        listenerList.remove(TreeModelListener.class, l);
    }

then you can make some helper method that creates event and notifies all listeners.

protected void fireTreeStructureChanged(Object source, Object[] path,
                                    int[] childIndices,
                                    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
        if (listeners[i]==TreeModelListener.class) {
            // Lazily create the event:
            if (e == null)
                e = new TreeModelEvent(source, path,
                                       childIndices, children);
            ((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
        }          
    }
}


another helper method
/**
  * Invoke this method if you've totally changed the children of
  * node and its childrens children...  This will post a
  * treeStructureChanged event.
  */
public void nodeStructureChanged(TreeNode node) {
    if(node != null) {
       fireTreeStructureChanged(this, getPathToRoot(node), null, null);
    }
}


and then call nodeStructureChanged() method when you change the three structure at some node.

probably your
data.refreshMe();
should call
nodeStructureChange(theRoot) after the reloading ...


0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1234838
take a look at

DefaultTreeModel.java for implementation techniques
DefaultTreeModel is a good TreeModel, because it informs all the listeners after each tree structure change ...


0
 

Author Comment

by:plaskowj
ID: 1234839
do you mean the resfresh method should be

  tree = new JTree();
  newModel = new DefaultTreeModel(data.top);//data is the adapter
  tree.setModel(newModel);


Refresh{
   data.refreshMe(); //refresh a method inside the model,
                       //which loads new info from db
   NewModel.reload();
   newModel.nodeStructureChanged(data.top);
}

0
 

Author Comment

by:plaskowj
ID: 1234840
i don't want listeners, i just want the tree to update on refresham i doing this right?
see above
0
 

Author Comment

by:plaskowj
ID: 1234841
data is just a class which gathers the info for nodes from a database
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1234842
can you explain waht TreeModel you use (DefaultTreeModel) and what functionality is implemented inside you 'data' adapter...
0
 

Author Comment

by:plaskowj
ID: 1234843
this is the tree model

DefaultTreeModel newModel = new DefaultTreeModel(data.top);

data is the instance of a class which makes up the nodes from a db

top is the root,

The only functionality in data is that of creating a Jtree from a db
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now