Java Reference
In-Depth Information
public String getTitle() {
return title;
}
public String getAuthors() {
return authors;
}
public float getPrice() {
return price;
}
}
To render a book as a node in the tree, you need to create a TreeCellRenderer implementation.
Because the topics are leaf nodes, the custom renderer will use a DefaultTreeCellRenderer to
render all the other nodes. The key part of the renderer is the getTreeCellRendererComponent() .
In the event that the node data received by this method is of type Book , it stores the appropriate
information in the different labels and returns a JPanel as the renderer, with labels for each of
the topic titles, authors, and prices. Otherwise, the getTreeCellRendererComponent() method
returns the default renderer.
Listing 17-4 contains the source for this custom renderer. Notice that it uses the same
selection colors as the remaining nodes of the tree so that the topic nodes don't appear out
of place.
Listing 17-4. Book Cell Renderer
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class BookCellRenderer implements TreeCellRenderer {
JLabel titleLabel;
JLabel authorsLabel;
JLabel priceLabel;
JPanel renderer;
DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();
Color backgroundSelectionColor;
Color backgroundNonSelectionColor;
public BookCellRenderer() {
renderer = new JPanel(new GridLayout(0, 1));
titleLabel = new JLabel(" ");
titleLabel.setForeground(Color.BLUE);
renderer.add(titleLabel);
authorsLabel = new JLabel(" ");
authorsLabel.setForeground(Color.BLUE);
renderer.add(authorsLabel);
priceLabel = new JLabel(" ");
priceLabel.setHorizontalAlignment(JLabel.RIGHT);
Search WWH ::




Custom Search