Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

ToolTips and Renderers

By default, JTree does not supply tooltips, but it does support the provision of tooltips via its renderer. If you want your tree to display tooltips, you have to do two things:

  • Register the tree with the ToolTipManager.

  • Arrange for the tree's renderer to return a tooltip as outlined here.

There are three ways to handle tree tooltips.

Using the Default Renderer

The simplest approach is just to have the tree return a single tooltip that applies to the entire tree. You can achieve this very easily if the tree uses a renderer that is actually subclassed from JLabel, which is true of the standard renderers. All you need to do in this case is register the tree with the tooltip manager and install the tooltip as a property of the renderer itself. Registering the tree with the ToolTipManager can be done using the following code, where the variable t is assumed to hold a reference to the tree:


and setting the tooltip is equally simple:

                  "Apollo and Skylab missions"); 

You can verify that this works by typing the command:

java JFCBook.Chapter10.ToolTipExample1 

If you move the mouse over the tree, after a short time the tooltip will appear.

Subclassing JTree

One problem with the approach just shown is that the tooltip appears only when the mouse is over a part of the tree drawn by a renderer. If this is not sufficient, you can subclass the JTree class to return a tooltip whenever the mouse is over it by overriding the getToolTipText method and using the JComponent setToolTipText method to store the tooltip that you want to display. When you take this approach, you don't need to register the tree with the ToolTipManager because this is done by the setToolTipText method: The appropriate implementation of the getToolTipText method is as follows:

public String getToolTipText(MouseEvent evt) {
  return getToolTipText();

This code probably looks a little strange! In fact, JComponent has two overloaded variants of getToolTipText:

public String getToolTipText(); 
public String getToolTipText(MouseEvent evt); 

The first of these two returns whatever string has been stored by the set-ToolTipText method. The second one allows a component to return a different tooltip based on the position of the mouse and is the one that is actually called by the ToolTipManager. The default implementation of this method in JComponent simply calls the other getToolTipText method, which is what our implementation does. The reason that we have to supply this code is that JTree itself overrides the second getToolTipText method to allow the tree's renderer to supply the tooltip, a fact that we used above (and will use again below) and, for this solution, we want to suppress JTree's code and revert to that in JComponent. You can try this code out using the command

java JFCBook.Chapter10.ToolTipsExample2 

This time, you'll find that the tooltip appears when the mouse is over any part of the tree.

Node-specific Tooltips Using a Custom Renderer

A third approach to the problem, and the most powerful, is to implement tooltip support in the renderer. This makes it possible to return a different tooltip for each node if necessary. As we said in the previous section, JTree overrides the getToolTipText method to get the tooltip for each node from that node's renderer. It does this by calling the renderer's getTree-CellRendererComponent method as if it were going to render the node and then invokes the getToolTipText method of the returned component to get the tooltip for the node. If you want your nodes to display tooltips, you simply have to call setToolTipText on the component that you return from the renderer's getTreeCellRendererComponent method.

To demonstrate the general technique, we'll modify the custom renderer shown in Listing 10–6 to include a tooltip. For simplicity, we'll make the tool-tip be the same text as would be displayed on the node itself. In a real-world application, you would probably store the tooltip as part of the node or its user object and code the renderer to extract it from there. Setting the tooltip requires only one extra line of code in the renderer's getTreeCellRen-dererComponent method:

// By default, use the same value as the
// node text for the tooltip, for leaf nodes only
            leaf ? value.toString() : null); 

where the variable c is the component being returned by the renderer. In this example, we set a tooltip only for leaf nodes.

Having made this change, you just need to register the tree with the Tool-TipManager, as shown earlier in this section, and your tree will display a different tooltip for each leaf node. However, as with the first approach we took to displaying tooltips, a tooltip will only be displayed when the mouse is over an area that will be drawn by a renderer. To arrange for a tooltip to be displayed wherever the mouse is, we can combine this approach with the previous one by subclassing JTree and implementing a cleverer version of getToolTipText:

public String getToolTipText(MouseEvent evt) {
  // Let the renderer supply the tooltip
  String tip = super.getToolTipText(evt); 

  // If it did not, return the tree's tip
  return tip != null ? tip : getToolTipText();

This code first calls the JTree implementation of getToolTipText, which allows the renderer to return a tooltip. If it does not supply one, then the tool tip set using setToolTipText is returned instead. Now, you can set a global tooltip using the JTree setToolTipText method and it will appear whenever the mouse is over a part of the tree that is not drawn by a renderer, or when the renderer itself returns a null tooltip which, in this case, would be for non-leaf nodes. You can try this out using the command

java JFCBook.Chapter10.ToolTipsExample3 

You'll find that a generic tooltip is displayed when the mouse is not over a leaf node and that each leaf node displays its own text as a tooltip. If you take this approach, you must register the tree with the ToolTipManager unless you invoke setToolTipText, in which case registration is handled for you.

Changing the Basic Look-and-Feel Specific Parts of a Tree

If your tree uses a look-and-feel that is derived from BasicTreeUI, you can customize more of its appearance. You can find out at runtime whether this is the case by getting a reference to its UI class by calling the JComponent getUI method and checking whether it is an instance of BasicTreeUI. If it is, as it will be for all of the standard look-and-feel implementations, you can make use of the methods shown in Table 10-6 to change the way in which the framework of the tree is drawn.

Table 10–6 Basic Tree Look-and-Feel Customization Methods



public void setLeftChildIndent(int)

Sets the horizontal distance between the left side of a node and the expansion handle for its children.

public void setRightChildIndent(int)

Sets the horizontal distance between the center of a node's expansion handle and the left side of its rendered cell.

public void setCollapsedIcon(Icon)

Sets the icon used to render the expansion handle when the node's children are not shown.

public void setExpandedI-con(Icon)

Changes the icon used as the expansion icon handle the node's children are on view.

Figure 10–12 shows the various configurable parts and how they affect the way in which the tree is rendered.

Figure 10–12 Basic Tree UI Customizable Items

These settings are applied everywhere in the tree—you can't have different settings for different rows. The icons that you supply are used to represent the expansion handle that appears to the left of a node that has children. Normally, this icon is a small circle with a "handle" extension or small square with a plus sign (+) in it when the node is collapsed and a minus sign (-) when it is expanded. The default icons are all fairly small. If you substitute larger ones, you will need to change the right or left indent values to space the remaining elements out horizontally. If your icon is taller than the standard ones, you'll need to increase the tree's row size, which you can do with the setRowHeight method of JTree. The next example adds these customizations to the tree that we have been using throughout this chapter. New expansion icons have been substituted and, since they are larger then the standard icons, the right child indentation and the row height have been increased to allow space for them. You can run this example for yourself using the command:

java JFCBook.Chapter10.CustomTree 

The result will look like that shown in Figure 10–13

Figure 10–13 A tree with customized expansion icons.

Here's the code that was added to the main method of the previous example, immediately after creating the tree, to make these changes. In this code, t holds a reference to the JTree object:

// Get the tree's UI class. If it is a BasicTreeUI,
// customize the icons
ComponentUI ui = t.getUI();
 if (ui instanceof BasicTreeUI) { 
  URL expandedURL = CustomTree.class.getResource(
  URL collapsedURL = CustomTree.class.getResource(
  ((BasicTreeUI)ui).setExpandedIcon(new ImageIcon(expandedURL));
  ((BasicTreeUI)ui).setCollapsedIcon(new ImageIcon(collapsedURL));

Since these customizations only work for a look-and-feel that bases its tree UI on BasicTreeUI, the first step is to use getUI to get the UI class. If it turns out that it is actually a BasicTreeUI, then new icons are loaded using the familiar ImageIcon class and used to customize the expansion handles. Note that extra space has been added between the expansion handle and the node itself to account for the fact that the customized icons for the expansion handles are larger than the default ones.

Changing Properties for All Trees

If you want to change the color of certain parts of a tree or the icons that it uses to represent open and closed folders and leaf nodes, and you want this change to apply to every tree in your application, you don't need to implement your own renderer or modify an existing one—instead, you can modify the UIDefaults table for the current look-and-feel, which maps property names to the values appropriate for the current look-and-feel. The tree has 19 useful properties that you can set in this way. These properties, together with the types of the associated objects, are listed in Table 10-7. The UIDe-faults table and the associated UIManager class are discussed in detail in Chapter 13.

Table 10–7 UIDefaults Properties for JTree

Property Name

Object Type







































If you want to change an entry in this table, there are two possible approaches depending on the effect you want to achieve. If you need the changes to stay in place if the user dynamically switches the look-and-feel (if you allow this—see Chapter 13), you should store Color, Font, Integer, Boolean, Border, or Icon objects in the UIDefaults table. When a look-and-feel switch occurs, these values will not be changed.

On the other hand, if the attributes you are setting only work with the current look-and-feel, you need to allow them to be reset to the new look-and-feel's defaults when a look-and-feel switch occurs. To achieve this, you need to wrap the attribute you are changing with an instance of BorderUIRe-source for a border, FontUIResource for a font, IconUIResource in the case of an icon, or ColorUIResource for a color. For example, to change the color of the text for a selected node to yellow only while the current look-and-feel is selected, you would proceed as follows:

UIDefaults defaults = UIManager.getDefaults();
          new ColorUIResource(Color.yellow)); 

or to change the color of the lines that connect the nodes to white, you might do this:

UIDefaults defaults = UIManager.getDefaults();
          new ColorUIResource(Color.white)); 

On the other hand, the following lines makes these changes permanent:

UIDefaults defaults = UIManager.getDefaults();
defaults.put("Tree.selectionForeground", Color.yellow); 
defaults.put("Tree.hash", Color.white); 

You can find out more about the UIDefaults table in Chapter 13. In general, it is a good idea to check whether you can carry out customization by modifying this table before using a more complex approach.

Editing a Tree's Nodes

By default, trees are read-only to the user but, if you wish, you can allow the user to change the value associated with any node in the tree with just one line of code:


If a tree is editable, you can edit the nodes by clicking on a node three times in quick succession or clicking once to select the node and then clicking again, having paused for a short time so that the two clicks do not get merged into a double-click (note that once a node is selected, a single click is enough to start the editing process), or by selecting a node and pressing the F2 key. Any of these gestures will causes the node's editor to appear. By default, the editor is a text field displaying the same text that represents the node in the tree. To edit the node, you just change the text and press RETURN. The editor will disappear and the new value will be installed.

To show how editing works, let's look at yet another version of the hardworking example program that we have used throughout this chapter, this time called EditableTree. The change to make it editable is just one line of code but, so that you can see what happened, a TreeModelListener is attached to the tree. When the editor accepts a change, it applies it to the tree model, which causes a TreeModelEvent. The code that was added to display the content of this event is shown below:


         new TreeModelListener() {
  public void treeNodesChanged(TreeModelEvent evt) {
    System.out.println("Tree Nodes Changed Event");
    Object[] children = evt.getChildren();
    int[] childIndices = evt.getChildIndices();
    for (int i = 0; i < children.length; i++) {
      System.out.println("Index " + childIndices[i] +
        ", changed value: " + children[0]);
  public void treeStructureChanged(TreeModelEvent evt) {
    System.out.println("Tree Structure Changed Event");
  public void treeNodesInserted(TreeModelEvent evt) {
    System.out.println("Tree Nodes Inserted Event");
  public void treeNodesRemoved(TreeModelEvent evt) {
    System.out.println("Tree Nodes Removed Event");

The event that the listener gets will indicate that one node has changed, so of the listener methods shown above, only treeNodesChanged will ever be called, but you are obliged to provide the others to implement the listener interface. The event handler extracts the list of changed indices from the event and the array of changed objects. Code is included to print a set of these but, in fact, there will only ever be one. The object in the array returned by getChildren is the DefaultMutableTreeNode for the node that was edited, so printing it will cause its toString method to be called that, as you know, will print the text associated with the node. If you run this program using the command

java JFCBook.Chapter10.EditableTree 

and change the text "Apollo" to "Shuttle," you'll see the following event generated:

Tree Nodes Changed Event 
Index 0, changed value: Shuttle 

To edit the tree cell, click the mouse over the text of value you want to change, then pause briefly and click again. If your clicks are too close together, nothing happens in the case of a leaf node, but if it's a branch node, you'll end up expanding or collapsing it instead of editing it. If you accidentally start editing a cell and don't want to continue, click anywhere else in the control or press the ESCAPE key and the edit will be aborted.

  • + Share This
  • 🔖 Save To Your Account