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: Help

[Magercise 2 | API Docs | Short Course | Magercises]

Help is available for each task, or you can go straight to the solution source code.

Task 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.

private JLabel renderer;

CellRenderer () {
  renderer = new JLabel();
  renderer.setOpaque (true);
}

Task 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.

public Component  getTreeCellRendererComponent(
    JTree tree, Object value, boolean selected,
    boolean expanded, boolean leaf, int row,
    boolean hasFocus) {

  // Get background color based on selected state
  Color background = (selected ? 
    Color.lightGray : Color.white);
  renderer.setBackground(background);

  if (leaf) {
    renderer.setText(value.toString());
  } else {
    renderer.setText("ROOT: "+value.toString());
  }
  return renderer;
}

If you would like to change the default image/icon displayed, call setIcon() with an Icon for the appropriate state.

Task 3

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

public TreePanel(TreeNode root, 
    TreeCellRenderer renderer) {
  // use layout that will stretch tree
  // to panel size
  setLayout(new BorderLayout());

  // Create tree
  JTree tree = new JTree(root);
  tree.setCellRenderer(renderer);
  ...
}

Task 4

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

CellRenderer cell = new CellRenderer();

Task 5

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

TreePanel tp = new TreePanel(component, cell);

Task 6

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

javac TreeRender.java
java TreeRender

The dependency checker automatically determines that TreePanel.java needs to be compiled.

Return to Magercise 2

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