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:

ToolTipManager.sharedInstance().registerComponent(t); 

and setting the tooltip is equally simple:

((JLabel)t.getCellRenderer()).setToolTipText( 
                  "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
 ((JComponent)c).setToolTipText( 
            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

Method

Description

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) { 
  ((BasicTreeUI)ui).setRightChildIndent(21);
  URL expandedURL = CustomTree.class.getResource(
                                "images/closebutton.gif");
  URL collapsedURL = CustomTree.class.getResource(
                                "images/openbutton.gif");
  ((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

Tree.background

Color

Tree.closedIcon

Icon

Tree.collapsedIcon

Icon

Tree.editorBorder

Border

Tree.expandedIcon

Icon

Tree.font

Font

Tree.foreground

Color

Tree.hash

Color

Tree.leafIcon

Icon

Tree.leftChildIndent

Integer

Tree.openIcon

Icon

Tree.rightChildIndent

Integer

Tree.rowHeight

Integer

Tree.scrollsOnExpand

Boolean

Tree.selectionBackground

Color

Tree.selectionBorderColor

Color

Tree.selectionForeground

Color

Tree.textForeground

Color

Tree.textBackground

Color


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();
defaults.put("Tree.selectionForeground",
          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();
defaults.put("Tree.hash",
          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:

tree.setEditable(true); 

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:

t.setEditable(true); 

t.getModel().addTreeModelListener(
         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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020