How can I get a node in a JTree file tree to know which file it is?

1.1k Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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