I'd like to color elements in a JTree. However, simply adding a background color only to the label looks kind of strange. Particularly if more than one node is selected, the resulting shape looks ragged and distracting.
Is there a way to make the background extend the whole width of the tree element, so that the whole row gets colored? Either starting at the left border or starting at the beginning of the label, but definitely extending till the right border of the component?
Here is a small self-contained demo, based on this question.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class SO26724913 {
public static void main(String[] args) {
DefaultMutableTreeNode a = new DefaultMutableTreeNode("a");
DefaultMutableTreeNode b = new DefaultMutableTreeNode("b");
DefaultMutableTreeNode c = new DefaultMutableTreeNode("c");
a.add(b);
a.add(c);
final JTree tree = new JTree(a);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent
(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean focus)
{
JComponent c = (JComponent)
super.getTreeCellRendererComponent
(tree, value, selected, expanded, leaf, row, focus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
String data = (String)node.getUserObject();
if ("b".equals(data)) {
c.setBackground(Color.RED);
c.setOpaque(true);
}
else {
c.setBackground(null);
c.setOpaque(false);
}
return c;
}
});
JFrame frm = new JFrame();
frm.getContentPane().add(tree);
frm.setSize(200, 200);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
This is what the code currently generates.
I'd prefer either this
or this.
getPreferredSize
instead makes sure the height is computed as usual. Computing the width of the whole tree will become impossible, though. Nevertheless, interesting approach, might be worth an answer so users can vote on this. – Yoontree.getWidth()
is zero inside my cell renderer. It seems that the cells are rendered to some buffered image, then the tree size is computed afterwards, and the cells are not rendered again. – Yoon