1

I wrote a file tree using JTree, and now I am trying to make it more efficient. I am trying to implement lazy loading, but I can't for the life of me get the nodes to recognize which file they are in order to expand the next layer. I've tried having them check their name against a list of the filenames on their level, and for some reason that doesn't work. That wouldn't work anyway in the long run. I have also tried setting the file itself as the node content, but it still won't recognize it as a file.

I'm sure I'm missing something simple, but I don't know what it would be. I've been searching around, and haven't found anything. Could anyone help me to figure this out?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
SaintWacko
  • 854
  • 3
  • 14
  • 35

2 Answers2

1

DefaultMutableTreeNode allows you to associate an arbitrary "user object", which in this case could be the File it represents. For example:

File file = new File("data.txt");
DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);

Then you simply need to add a TreeSelectionListener to the JTree and interrogate the selected DefaultMutableTreeNode to obtain its File and take appropriate action based on whether it represents a directory or a file.

Adamski
  • 54,009
  • 15
  • 113
  • 152
  • How do I interrogate it to get that? The way you suggested is how I've been doing it, but for some reason it doesn't seem to see it as a file. Or perhaps my problem is the way it retrieves the node? The place I learned how to make the filetree had it written such: `public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();` Does that cause it to no longer contain its user object? – SaintWacko Nov 16 '11 at 23:03
  • Bah, edit limits. Ignore my previous comment, I discovered the problem. I had accidentally let part of the code setting nodes as strings instead of files. I also had it on Select instead of Will Expand. Got all that fixed now, only thing left to do is figure out why it just stacks the top node all the way down, but that should be easy. Thanks for the help! – SaintWacko Nov 16 '11 at 23:43
1

Rather than implementing lazy tree loading with a TreeWillExpandListener. Just use a custom tree model that only bothers to examine files when necessary. A good example of an existing FileTreeModel that does that can be found here

heneryville
  • 2,853
  • 1
  • 23
  • 30