Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Online Training

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
Print Button
 
Training Index

Magercise 2
Custom JTree Rendering

[Help | API Docs | Short Course | Magercises]

Magercise 2 Prerequisites

Tree Views

Skeleton Code

A JTree component has a default view for contained elements—the String representation of the object and a open/closed turner icons for nonleaf nodes. In this magercise, you will modify the default behavior to display just the string representation. For nonleaf nodes, you will add "ROOT:" to the string displayed. Also, for the selected cell, have the cell background be light gray.

Tasks:

  1. The TreeRender skeleton contains an inner class CellRenderer that implements the TreeCellRenderer interface. First, create a constructor that creates a JLabel to use as a renderer, be sure to make it opaque.

  2. The TreeCellRenderer interface describes how a cell is rendered in a tree. It consists of the method getTreeCellRendererComponent().

    Implement the getTreeCellRendererComponent() method, such that the text of the renderer is the string representation of the object passed in. For nonleaf nodes, prefix the string with "ROOT:". Change the background color to light gray for selected nodes and return the label used as the renderer.

  3. Modify the constructor for TreePanel so that its constructor accepts a TreeCellRenderer. Then, call setCellRenderer() on the tree to change the renderer.

  4. In the TreeRender constructor, create a CellRenderer. You'll need to pass this along to the TreePanel constructor that you just modified.

  5. Add the tree cell rendered to the parameter list to the TreePanel constructor.

  6. Save everything and compile the program. Then run it to see the results.

[Result]

Where help exists, the task numbers above are linked to the step-by-step help page.

Solution

The following JavaTM source files represent a solution to this Magercise:

Magercise 3

Short Course

About This Short Course

Copyright © 1998-1999 MageLang Institute. All Rights Reserved.


Print Button
[ This page was updated: 21-Sep-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary | Feedback | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.