19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

In graph theory, depth-first traversal is defined the<br />

same as preorder traversal, but in the<br />

depthFirstEnumeration() method in DefaultMutableTreeNode,<br />

it is the same as pos<strong>to</strong>rder traversal.<br />

NOTE<br />

<br />

You can create a JTree from a root using new<br />

JTree(TreeNode) or from a model using new<br />

JTree(TreeModel). To create a tree model, you first<br />

create an instance of TreeNode <strong>to</strong> represent the root of<br />

the tree, and then create an instance of DefaultTreeModel<br />

fitted with the root.<br />

Listing 40.14 gives an example that creates two trees <strong>to</strong> display<br />

world, continents, countries, and states. The two trees share the<br />

same nodes and thus display identical contents. The program also<br />

displays the properties of the tree in a text area, as shown in<br />

Figure 40.24.<br />

Figure 40.24<br />

The two trees have the same data because their roots are the same.<br />

Listing 40.14 TreeNodeDemo.java<br />

<br />

<br />

<br />

<br />

1 import java.awt.*;<br />

2 import javax.swing.*;<br />

3 import javax.swing.tree.*;<br />

4 import java.util.*;<br />

5<br />

6 public class TreeNodeDemo extends JApplet {<br />

7 public TreeNodeDemo() {<br />

8 // Create the first tree<br />

9 DefaultMutableTreeNode root, europe, northAmerica, us;<br />

10<br />

11 europe = new DefaultMutableTreeNode("Europe");<br />

12 europe.add(new DefaultMutableTreeNode("UK"));<br />

13 europe.add(new DefaultMutableTreeNode("Germany"));<br />

39

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!