Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Tree Appearance

To emphasize how dependent the appearance of a tree and its nodes are on the selected look-and-feel, let's look at some of the possible variations. Figure 10–1 shows a tree with the Metal look-and-feel selected. The same tree in the Windows look-and-feel is shown in Figure 10–2, while the Motif version can be seen in Figure 10–3.

It's pretty evident that there are differences between these figures and Figure 10–1. As you can see, Windows and Motif use boxes to indicate nodes that have children. When the children are invisible, the expansion box has a plus sign to indicate that there is more of the tree to be viewed; when you open such a node to show its children, the plus sign changes to a minus sign, as you can see in the case of the C:\WINDOWS\SYSTEM node. The icons are also subtlly different and the line styles vary between look-and-feel implementations.

It is even possible to have different representations of the same tree within a single look-and-feel. The tree has a client property called lineStyle that is used to control the lines drawn between nodes. This property is currently supported only by the Metal look-and-feel, but there is nothing about the mechanism used to implement it that binds it to a single look-and-feel, so you may find it implemented more widely in the future. The lineStyle property has three possible values, listed in Table 10-1.

Table 10–1 LineStyle Settings

Setting

Effect

None

No lines are drawn anywhere on the tree.

Angled

Vertical lines between nodes at the same level, horizontal line to child node.

Horizontal

A single horizontal line between nodes immediately attached to the root node. This is the default setting.


Figure 10–1 shows a tree with the Angled setting, which is the most natural way to represent a file system and is most like the appearance of Windows and Motif trees. This configuration can be obtained using code like this:

Jtree tree = new Jtree() ;

Figure 10–2 A tree as drawn by the Windows look-and-feel

Figure 10–3 A Motif tree.

Tree.putClientProperty("Jtree.lineStyle", "Angled");

Similar code is required to obtain the other two possible effects. The same tree rendered with lineStyle set to None is shown in Figure 10–4 and with lineStyle set to Horizontal in Figure 10–5. Because None is the default, all of your trees will look like the one in Figure 10–4 if you don't explicitly select a lineStyle. Since lineStyle is ignored by look-and-feel implementations that don't provide it, it is always safe to set a specific value no matter which look-and-feel is selected.

Tree Node Selection

The mouse can be used to select an item from the tree by clicking on the icon or the text. Clicking twice on either of these is the same as clicking on the expansion handle—the node either expands or collapses depending on its current state. The ability to make a selection is one of the main reasons for using a tree control. As you'll see, you can attach listeners that receive notifi-cation when a selection is made and you can also arrange to be notified when part of the tree is expanded or collapsed or is about to do so.

Figure 10–4 A Metal tree with line style "None."

Elements of the Tree

Now let's turn to how a tree is represented in terms of data structures. The only elements of any substance in a tree are the nodes themselves—the way in which these nodes relate to each other is represented by references from one node to another. The JTree control doesn't directly manage the nodes themselves, or remember how they are organized. Instead, it delegates this to its data model.

As with the other Swing components, JTree deals mainly with generic objects that are represented in Java by an interface. For example, any class can be used as a data model for the tree, so long as it implements the Tree-Model interface and any class can participate in the model as a node in the tree so long as it implements the interface TreeNode. This design pattern has been shown before in connection with JComboBox and JList, which have data models specified as interfaces and concrete implementations of those interfaces that are used by default. The JTree (and, to some extent JTable) is a little different from JComboBox and JList in that it is not really good enough to just implement the TreeNode and TreeModel interfaces. The default implementations of these interfaces in the Swing tree package provide facilities far beyond those specified by TreeNode and TreeModel. Furthermore, in many cases, these extra facilities can be accessed directly through the model or indirectly via the JTree object and there will be a loss of functionality if classes that only implement the minimal interface are used instead of the default ones. In practice, tree nodes are most likely to be instances of the class DefaultMutableTreeNode, while the model will probably be derived from DefaultTreeModel. For specific, lightweight uses of the tree where the full functionality of DefaultMu-tableTreeNode and DefaultTreeModel are not required, it might be useful to develop less functional implementations.

Figure 10–5 A Metal tree with line style "Horizontal."

JTree is unlike JComboBox and JList in another way. When you create either of the latter two, you populate the model and then wait for a selection. The item that is retrieved from the control as the user's selection is of the same type as the data held within the model itself. For example, a list box populated with Strings would return a selected item of type String. With JTree, things are not so simple. The model deals in terms of nodes, but the user interface to the tree uses a class called TreePath and the immediate result of a selection is one or more TreePaths. As you'll see later, there is a way to map from a TreePath to the corresponding TreeNode, which means that it is possible, from an event listener, to get back to the original node in the data model. This node is not, however, of any direct use to the selection event handler unless some information has been stored with the node that is of meaning to the user of the tree. Suppose, for example, that you construct a tree that shows the content of a file system in a file open dialog and the user double-clicks on an item to have it returned to the tree user as the selected file. There are two ways that the interface to the user of this tree could be built—either the name of the selected file would be returned, or alternatively you could choose to return an object that represents the file that was stored with the file's node when the tree was created. The second of these alternatives is obviously more powerful. To make such an implementation possible, the tree nodes allow you to store a reference to an arbitrary object, called the user object, with each node. How you use this is up to you—you might just choose to make it the file's name, or it might be a java.io.File object for the file.

Creating a Tree

JTree has no less than seven constructors, most of which allow you to initialize the data model with a small quantity of data taken from the more common data collection classes in the JDK:

public JTree();
public JTree(Hashtable value);
public JTree(Vector value);
public JTree(Object[] value); 
public JTree(TreeModel model); 
public JTree(TreeNode rootNode); 
public JTree(TreeNode rootNode,
              boolean askAllowsChildre); 

The first constructor gives you a tree with a small data model already installed; this can be useful when you write your first program that uses a tree, but after that you'll probably never use it again. The next three constructors initialize the tree from a Hashtable, a Vector, and an array of arbitrary objects. Since all of these are flat data structures, the resulting tree is also flat, consisting of a root node and the data from the object passed to the constructor attached to it, with one node per entry in the table, vector or array. Figure 10–6 shows a tree created from a Hashtable containing five entries.

Figure 10-6 A tree created from a Hashtable.

The code that was used to create this tree is shown in Listing 10-1 and can be run using the command

java JFCBook.Chapter10.HashHandleTree. 

Listing 10–1 Creating a Tree with a Hashtable

package JFCBook.Chapter10; 

import javax.swing.*;
import javax.swing.tree.*; 
import java.util.*; 
public class HashHandleTree {
  public static void main(String[] args) { 
    JFrame f = new JFrame("Tree Created From a Hashtable");
    Hashtable h = new Hashtable();
    h.put("One", "Number one");
    h.put("Two", "Number two");
    h.put("Three", "Number three");
    h.put("Four", "Number four");
    h.put("Five", "Number five");
    JTree t = new JTree(h);
    t.putClientProperty("JTree.lineStyle", "Angled"); 

    t.setShowsRootHandles(false);
    f.getContentPane().add(t);
    f.pack();
    f.setVisible(true);
  }
}

As you can see from Figure 10–6, the tree displays all of the items from the Hashtable. Each item has been turned into a leaf node and added directly beneath the root node of the tree. However, since a root node was not explicitly supplied, the tree doesn't display one. This is a common feature amongst trees created with the second, third, and fourth constructors. A consequence of this is that you can't collapse this tree. You can force the root node to be displayed by using the JTree setRootVisible method:

t.setRootVisible(true); 

This would show the root node as an open folder labeled root, with an expansion icon to the left of it. If you don't want to show the expansion icon, you can disable it using setShowsRootHandles:

t.setShowsRootHandles(false); 

Figure 10–7 shows two trees, both with the root node visible. The left-hand tree was created with setShowsRootHandles(true) and the right one with setShowsRootHandles(false).

Figure 10–7 A tree with the root visible.

You can expand or collapse the tree by double-clicking on the root folder or its label. You can also use the keyboard to navigate the tree and open or close nodes. If you select the root node, you can use the down arrow key to move down the set of child nodes and the up key to move back up again. When a node that has children is selected and closed, the right arrow key will open it. Similarly, you can use the left arrow key on an open branch node to close it.

In cases like this where the root node was created automatically, the arbitrary label root is assigned to it. You can, if you wish, change this label or remove it entirely. You'll see how to do this later.

You'll notice that the items in the tree are not ordered in a particularly sensible way. This happens because Hashtables don't maintain the order of the items that you place into them. The tree is constructed by getting an enumeration of the items in the Hashtable, which doesn't guarantee any particular ordering. If you care about the order in which the data is displayed, you should use a Vector or an array.

Most trees will be created using one of the last three constructors, which require a complete tree model or at least the root node to have already been constructed. If you choose to supply a model, you can use the Swing DefaultTreeModel class, or create your own as long as it implements the TreeModel interface. For most purposes, DefaultTreeModel is more than adequate and, as mentioned earlier, it offers useful facilities over and above the basic interface, many of which will be used in this chapter.

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