views:

714

answers:

4

I'm looking for a threaded solution to updating my JTree every second.

Basically, I'm...

  • Importing an external file
  • Creating an Enumeration off of that
  • Building the tree off the enumeration

The external file can change at random, and the data in the tree needs to represent this change in a somewhat reasonable time manner. How would I be able to have the tree redraw without repainting the entire content pane which the JTree (via a panel) is in?

Thanks!

A: 

If you repaint the JTree component, the paint region will be clip out the rest of the containing panel.

Tom Hawtin - tackline
+2  A: 

Just have the JTree's model fire an update, and the JTree will repaint itself. The easiest way to do this is to use a DefaultTreeModel, and when the file changes, construct TreeNodes (possibly using DefaultMutableTreeNode) from your file, and call setRoot() on the model with the base node of your newly created node tree.

CarlG
A: 

I would do something like @Tom suggested if you have lots of nodes. The solution of @CarlG is probably fine for few nodes. If you update the entire tree model, every second you run into performance issues.

I would update only the visible bounds of the tree, if needed, and keep some AST(Syntax tree) somewhere. If the tree model(from the parsed document) is changing every second, I seriously doubt that the user will have time to scroll all the tree each second.

User scrolled to bounds XXX
A = First visible node
B = Last visible node
if someRangeBefore(A) is dirty update
If region(A, B) is dirty
  update nodes

It would be more complicated than above to implement a working and very efficient strategy to update nodes.

John Doe
A: 

I guess you probably read this somewhere else: Swing is not thread save ;). If you want to update a Swing component from a different thread anyway, you have to make that other thread push it's updates on Swing's event thread. The method to do this is EventQueue.invokeAndWait(Runnable).

Here's a code example for a similar problem (making a JTree sync with a directory tree): http://www.onyxbits.de/content/java-and-directory-trees-joy-implementing-simple-filemanager

You should be interested in the FileMonitor.java file.

Patrick