JTree and JList: data reference

Posted on 1997-11-15
Last Modified: 2008-03-04
I want to put something together like the Windows Explorer.
A JTree on the left showing a hierarchy, a JList presenting
the contents of a selected node.

How do I get references to actual data into a JTree and
a JList? It is quite easy to fill both with strings.
But how do I get a reference to the underlying data of
each node? Is it possible to store a reference together
with the string in a node?

I want double click a node and then a window with
the respective data comes up! Consequently I will
have to supply the MouseListener with some data!

Regards, Lewis.
Question by:Lewis
  • 6
  • 5

Accepted Solution

mnelson051997 earned 200 total points
Comment Utility
You can store File (or TypedFile) objects within the JTree.
Then when double clicked, you can go to the File/TypedFile
and actually read it.  You can make it display properly by
creating your own TreeCellRenderer which extends JLabel.  In
the getTreeCellRendererComponent(...) method, you can get
the File/TypedFile object from the value parameter using the
getUserObject() method.  Then set the JLabel text and icon
values based on it.

Author Comment

Comment Utility
Thanks for the information,
but the data I want to display is not stored
in files, I get it from another server.

So, I need to store general information in a
node, not File objects. Is it possible to
put objects of type Object there?

Do you know anything about JList, concerning
the same problem?

Expert Comment

Comment Utility
You can put any object you want into a DefaultMutableTreeNode.
You can also put any object you want into a JList's
ListModel.  I believe that by default the TreeCellRenderer
and ListCellRenderer will call the object's toString()
method and get the string to display that way.  So, you can
either make your objects put out their text that way and
use the default renderer, or you can create custom cell
renderers if you want more control.

Author Comment

Comment Utility
I just yesterday found that information about
models (MVS).
Can you explain (in easy words) this model
idea to me? I haven't quite understood it!

Expert Comment

Comment Utility
I'll give it a shot.  Most JFC components are made up of three

1)  The component class like JTree or JButton.  This class
stores information about the external state of itself --
things like its border, button icon, button text, background
color, etc.
2)  The model class like DefaultButtonModel or DefaultTreeModel.
This class stores data associated with the component (like the
tree nodes) and internal state information (like whether a
button is pressed, whether the component is disabled, etc.).
For JTree, the model class also allows access to the tree's
3)  A look-and-feel class like BasicButtonUI.  This class
is responsible for drawing the component.  For a JButton, it
asks the JButton class for its text string and icon (if any),
and asks the DefaultButtonModel (which it gets from the JButton
class) for information about whether the button is pressed,
etc. so it can draw the component properly.  This class doesn't
store data itself because a different look-and-feel could be
plugged-in at any moment and BasicButtonUI could be replaced
with something like RoseButtonUI.  The look-and-feel class
is also responsible for reacting to events like mouse clicks
within itself.  So, when you press on a JButton, the look-and-
feel class is notified.  It then asks the model class if it
is enabled.  If so, it tells the model it is now pressed and
repaints itself.  When the mouse is then released, the look-
and-feel class tells the model class that it is no longer
pressed and generates an ActionEvent which is broadcast to
any registered ActionListeners.

This is a somewhat simplified explanation of a topic that
still confuses me, but I hope it helps.

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.


Author Comment

Comment Utility
So, if I understand you correctly, I have to build a
model of my tree to store the data?

Could you give me example code of
1) how to associate data with a tree node
   (in my case I would have to store something
    like: "CN=Peter,OU=Sales Dept.,O=Company Inc., C=US"
    which is the reference to an entry in an LDAP
2) how to put a Listener into the whole thing
   (When I double click the tree node "Peter"
    from the example above I need to get that
    reference back and put it in a method call
    This method will then return the values
    which refer to "Peter", like his e-mail
    address, his age, ...)

Expert Comment

Comment Utility
To create a DefaultMutableTreeNode with an object in it:

// Create the object.
String nodeString1 = new String( "CN=..." );
// Create the node.
DefaultMutableTreeNode node =
                    new DefaultMutableTreeNode( nodeString1 );

You create a root node and you can either explicitly use
it to create a DefaultTreeModel, or you can create a JTree
with the node and that implicitly creates a DefaultTreeModel:

JTree tree = new JTree( node );

To find out which node was double-clicked, listen for the
JTree's mouse events, and when you get a double-click, use
the MouseEvent's x and y coordinates to ask the JTree for
the node at that location.  Use the getPathForLocation(..)
method.  That gives you a TreePath, and you can use its
getLastPathComponent() method to get the actual double-
clicked node.  Then call the node's getUserObject() method
to get its contents.

Author Comment

Comment Utility
Sorry, but it took me a while to figure this out.
You certainly wait for your points.

Final questions:
1. I can put any Object into a DefaultMutableTreeNode
   and the toString method of that object is responsible
   for delivering a String that is displayed by the tree?
2. I have to check the x and y position in order to
   find a selected node? No better way?
3. I don't have to register a Listener with every node?
   Instead I provide on [?]TreeListener and pass the node
   to it that I just found out via the TreePath?
4. What exatly are TreePaths? Objects that contain an
   absolute path?
5. What's the difference between calling JTree with
   a DefaultTreeModel versus DefaultMutableTreeNode?


Expert Comment

Comment Utility
Yes, I believe DefaultMutableTreeNode displays the user
object's toString() result.

To track selections in a JTree, register your class as a
TreeSelectionListener.  Then, when you are notified of a
tree selection change (the valueChanged() method is called),
you can get the path of the selected node using the
TreeSelectionEvent's getPath() method, then you can use1
TreePath's getLastPathComponent() method.

You definitely do not need to register with each node.  As
long as you register as a TreeSelectionListener, you will
be notified when any node is selected or deselected.

A TreePath is basically a thing that contains an array of
TreeNodes that gets you from one node (usually root) to
another node.  When you get a selected TreePath, the
node that is actually selected is the last node in the

When you create a JTree with a DefaultMutableTreeNode, the
JTree takes care of creating the DefaultTreeModel.  So,
there really isn't much difference.

Author Comment

Comment Utility
Do you anything about memory usage?
Do I have to free the whole tree
recursively if I do not need it any
longer? Or is it sufficient to set
root to null and let the garbage
collector take care of it?

Anyway, here are your points.
Thanks, your advice was very helpful!

Expert Comment

Comment Utility
Yes, just set root to null and the garbage collector will
deal with the rest.

Good luck!

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
network + 7 73
count11 challenge 6 47
mapBully challenge 6 88
Java Message handling in Service Layer 3 37
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

743 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

18 Experts available now in Live!

Get 1:1 Help Now