Java Reference
In-Depth Information
21
public void displayTree() {
22
this .getChildren().clear(); // Clear the pane
clear the display
23
if (tree.getRoot() != null ) {
24
// Display tree recursively
25
displayTree(tree.getRoot(), getWidth() / 2 , vGap,
display tree recursively
26
getWidth() / 4 );
27 }
28 }
29
30 /** Display a subtree rooted at position (x, y) */
31 private void displayTree(BST.TreeNode<Integer> root,
32 double x, double y, double hGap) {
33 if (root.left != null ) {
34 // Draw a line to the left node
35 getChildren().add( new Line(x - hGap, y + vGap, x, y));
36
connect two nodes
// Draw the left subtree recursively
37
displayTree(root.left, x - hGap, y + vGap, hGap / 2 );
draw left subtree
38 }
39
40 if (root.right != null ) {
41 // Draw a line to the right node
42 getChildren().add( new Line(x + hGap, y + vGap, x, y));
43
connect two nodes
// Draw the right subtree recursively
44
displayTree(root.right, x + hGap, y + vGap, hGap / 2 );
draw right subtree
45 }
46
47 // Display a node
48 Circle circle = new Circle(x, y, radius);
49 circle.setFill(Color.WHITE);
50 circle.setStroke(Color.BLACK);
51
getChildren().addAll(circle,
display a node
52
new Text(x - 4 , y + 4 , root.element + "" ));
53 }
54 }
In Listing 25.9, BSTAnimation.java, a tree is created (line 14) and a tree view is placed in the
pane (line 18). After a new key is inserted into the tree (line 37), the tree is repainted (line 38)
to reflect the change. After a key is deleted (line 49), the tree is repainted (line 50) to reflect
the change.
In Listing 25.10, BTView.java, the node is displayed as a circle with radius 15 (line 48).
The distance between two levels in the tree is defined in vGap 50 (line 25). hGap (line 32)
defines the distance between two nodes horizontally. This value is reduced by half ( hGap / 2 )
in the next level when the displayTree method is called recursively (lines 44, 51). Note that
vGap is not changed in the tree.
The method displayTree is recursively invoked to display a left subtree (lines 33-38)
and a right subtree (lines 40-45) if a subtree is not empty. A line is added to the pane to con-
nect two nodes (lines 35, 42). Note that the method first adds the lines to the pane and then
adds the circle into the pane (line 52) so that the circles will be painted on top of the lines to
achieve desired visual effects.
The program assumes that the keys are integers. You can easily modify the program with
a generic type to display keys of characters or short strings.
Tree visualization is an example of the model-view-controller (MVC) software architec-
ture. This is an important architecture for software development. The model is for storing and
handling data. The view is for visually presenting the data. The controller handles the user
interaction with the model and controls the view, as shown in FigureĀ 25.18.
 
Search WWH ::




Custom Search