Technical Support
Discussion Forum
Online Training
Technical Articles
Bug Parade
JDC Resources
DukeDollars
Early Access
Toolbar
Community Process
Technology Sites

JDC Home Page

Solaris Developer Connection

Java Technology
java.sun.com

Java Industry Connection

Log Out

Online Training
SearchFAQContact Us

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 Java™ source files represent a solution to this Magercise:

Magercise 3

Short Course

About This Short Course

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





Questions?
29-Mar-99
Copyright © 1996-1999 Sun Microsystems Inc.
All Rights Reserved. Legal Terms. Privacy Policy.
Sun Microsystems