Reputation: 11
there is a lot of similar topics that I've seen here but couldn't really find solution to my little problem.
My application is searching through a file and showing the results inside a jtree. and I have a problem with that. When I add new nodes to a tree using insertNodeInto(...); i can search through found items while still searching but there is a problem with visualization. I mean there is a problem with rendering the nodes - I really can't explain that properly so I'm including this image.
When I use reload on jtree at the end of searching everything is back to normal - rendering is ok, unfortunately this closes all tabs that user opened.
I'm a student - sorry for my poor english. I hope someone know why this problem appears.
Upvotes: 1
Views: 844
Reputation: 39495
The way that your GUI is displayed, it certainly looks as if you are adding components to your Model outside of the painting thread (the Event Dispatch Thread (EDT)). This in turn will trigger painting outside of this thread, which will result in erratic painting.
Please take a look at this tutorial on threads in Swing
Looking at DefaultTreeModel
, it is clear that the insertNodeInto(..)
method will trigger the GUI updates, so if not done on the EDT, you are prone the painting issues depicted in your example.
A quick fix would be to add a method similar to the (uncompiled) code below:
public void safeInsertNodeInto(final MutableTreeNode newChild,
final MutableTreeNode parent, final int index) {
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
model.insertNodeInto(newChild,parent,index);
}
}
);
}
then call that method instead of directly calling on you model.
That said, I heavily recommend reading the tutorial cited above. There are more advanced ways of dealing with the EDT constraints.
Upvotes: 2