Author: Zafir Anjum
Add a background image to the JTree. You can use this to display your company logo or an evaluation image in a trialware.
Note that this implementation causes the background image to scroll with the tree content.
Using the right CellRenderer is very important for this to work. The DefaultTreeCellRenderer does not work too well.
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class Tree
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Table");
frame.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
Window win = e.getWindow();
win.setVisible(false);
win.dispose();
System.exit(0);
}
} );
JTree tree = new JTree()
{
ImageIcon image = new ImageIcon( "codeguruwm.gif" );
public void paint( Graphics g )
{
// First draw the background image - tiled
Dimension d = getSize();
for( int x = 0; x < d.width; x += image.getIconWidth() )
for( int y = 0; y < d.height; y += image.getIconHeight() )
g.drawImage( image.getImage(), x, y, null, null );
// Now let the regular paint code do it's work
super.paint(g);
}
};
// Set the tree transparent so we can see the background image
tree.setOpaque( false );
tree.setCellRenderer( new MyCellRenderer() );
JScrollPane sp = new JScrollPane( tree );
frame.getContentPane().add( sp );
frame.pack();
frame.show();
}
}
class MyCellRenderer extends JLabel implements TreeCellRenderer
{
public MyCellRenderer()
{
setOpaque(false);
setBackground(null);
}
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
{
setFont(tree.getFont());
String stringValue = tree.convertValueToText(value, sel,
expanded, leaf, row, hasFocus);
setEnabled(tree.isEnabled());
setText(stringValue);
if(sel)
setForeground(Color.blue);
else
setForeground(Color.black);
if (leaf) {
setIcon(UIManager.getIcon("Tree.leafIcon"));
} else if (expanded) {
setIcon(UIManager.getIcon("Tree.openIcon"));
} else {
setIcon(UIManager.getIcon("Tree.closedIcon"));
}
return this;
}
}
Posted On: 17-Jan-1999