Please have a look at the SSCCE. How can I make the non-selected tree nodes\' background transparent. At the moment the background of non-selected nodes is white. My cell re
You should override getBackgroundNonSelectionColor,getBackgroundSelectionColor and getBackground of DefaultTreeCellRenderer
and return appropriate values like so:
public class MyCellRenderer extends DefaultTreeCellRenderer {
@Override
public Color getBackgroundNonSelectionColor() {
return (null);
}
@Override
public Color getBackgroundSelectionColor() {
return Color.GREEN;
}
@Override
public Color getBackground() {
return (null);
}
@Override
public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean sel, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) {
final Component ret = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
final DefaultMutableTreeNode node = ((DefaultMutableTreeNode) (value));
this.setText(value.toString());
return ret;
}
}
which will produce:
Other suggestions:
JFrame
unnecessarily rather create an instance and use that.setSize
on JFrame
rather use a correct LayoutManager
and/or override getPreferredSize()
and call pack()
on JFrame
before setting it visible but after adding all components.JFrame#setDefaultCloseOperation
with either DISPOSE_ON_CLOSE
or EXIT_ON_CLOSE
(DISPOSE_XXX
is usually preferred unless using Timer
s as this will allow main(String[] args)
to continue its execution after Gui has been closed).To avoid background refilling, just put UIManager.put("Tree.rendererFillBackground", false);
before new SimpleTree();
or after super("Creating a Simple JTree");
.