Reputation: 307
To put it simply: why doesn't the following small example show a light gray background on the third item in the tree control?
The code creates a JTree, populates it with three strings (directly passed in to the constructor) and overrides the getCellRenderer() method to return an instance of the custom MyTreeCellRenderer class, which has a hard-coded check to set the background color of any cell on row 2 to light gray. But when run, all cells just have the regular (white) background color.
import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
public MainFrame() {
final MyTreeCellRenderer treeRenderer = new MyTreeCellRenderer();
JTree tree = new JTree(new Object[] { "First", "Second", "Third" }) {
@Override
public TreeCellRenderer getCellRenderer() {
return treeRenderer;
}
};
tree.setRootVisible(false);
add(tree);
setSize(400, 300);
setVisible(true);
}
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component c = super.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, hasFocus);
if (row == 2) {
c.setBackground(Color.LIGHT_GRAY);
} else {
c.setBackground(Color.WHITE);
}
return c;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame();
}
});
}
}
Upvotes: 2
Views: 325