Java Reference
In-Depth Information
public void run() {
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> oneVector = new NamedVector<String>("One", args);
Vector<String> twoVector = new NamedVector<String>("Two",
new String[]{"Mercury", "Venus", "Mars"});
Vector<Object> threeVector = new NamedVector<Object>("Three");
threeVector.add(System.getProperties());
threeVector.add(twoVector);
Object rootNodes[] = {oneVector, twoVector, threeVector};
Vector<Object> rootVector = new NamedVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
frame.add(tree, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Scrolling Trees
If you created and ran the program in Listing 17-2, you would notice one small problem. When
all the parent nodes are open, the tree is too big for the initial screen size. Not only that, but you
also can't see the nodes at the bottom of the tree. To fix this situation, it's necessary to place
instances of the JTree class within a JScrollPane so that the scroll pane can manage the scrolling
aspects of the tree. Similar to the JTextArea class described in Chapter 15, the JTree class
implements the Scrollable interface for scrolling support.
Replacing the two boldfaced lines in the example in Listing 17-2 with the following three
lines will place the tree within a scroll pane. This will cause the tree to appear in a scrollable
region when the tree is too large for the available display space.
// Change from
JTree tree = new JTree(rootVector);
frame.add(tree, BorderLayout.CENTER);
// To
JTree tree = new JTree(rootVector);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
In addition to using a JScrollPane for scrolling, you can manually scroll the visible content
in the scrolling region. Use the public void scrollPathToVisible(TreePath path) and public
void scrollRowToVisible(int row) methods to move a particular tree path or row into some
part of the visible area. The row of a node indicates the number of nodes above the current
node to the top of the tree. This differs from the level of the tree, which is the number of ancestors
(or parent nodes) a node has. Figure 17-3 should help you visualize this difference. In the
Search WWH ::




Custom Search