Java Reference
In-Depth Information
Example 10•20: ComponentTree.java (continued)
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected,
boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
String newvalue = value.getClass().getName(); // Component type
String name = ((Component)value).getName(); // Component name
if (name != null) newvalue += " (" + name + ")"; // unless null
// Use the wrapped renderer object to do the real work
return renderer.getTreeCellRendererComponent(tree, newvalue,
selected, expanded,
leaf, row, hasFocus);
}
}
/**
* This main() method demonstrates the use of the ComponentTree class: it
* puts a ComponentTree component in a Frame, and uses the ComponentTree
* to display its own GUI hierarchy. It also adds a TreeSelectionListener
* to display additional information about each component as it is selected
**/
public static void main(String[] args) {
// Create a frame for the demo, and handle window close requests
JFrame frame = new JFrame("ComponentTree Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
// Create a scroll pane and a "message line" and add them to the
// center and bottom of the frame.
JScrollPane scrollpane = new JScrollPane();
final JLabel msgline = new JLabel(" ");
frame.getContentPane().add(scrollpane, BorderLayout.CENTER);
frame.getContentPane().add(msgline, BorderLayout.SOUTH);
// Now create the ComponentTree object, specifying the frame as the
// component whose tree is to be displayed. Also set the tree's font.
JTree tree = new ComponentTree(frame);
tree.setFont(new Font("SanssSerif", Font.BOLD, 12));
// Only allow a single item in the tree to be selected at once
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
// Add an event listener for notifications when
// the tree selection state changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
// Tree selections are referred to by "path"
// We only care about the last node in the path
TreePath path = e.getPath();
Component c = (Component) path.getLastPathComponent();
// Now we know what component was selected, so
// display some information about it in the message line
if (c.isShowing()) {
Point p = c.getLocationOnScreen();
msgline.setText("x: " + p.x + " y: " + p.y +
" width: " + c.getWidth() +
Search WWH ::




Custom Search