I am using this below piece of code:
class CountryTreeCellRenderer implements TreeCellRenderer {
private JLabel label;
CountryTreeCellRenderer() {
label = new JLabel();
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof Country) {
Country country = (Country) o;
label.setIcon(new ImageIcon(country.getFlagIcon()));
label.setText(country.getName());
} else {
label.setIcon(null);
label.setText("" + value);
}
return label;
}
}
Since I am passing/returning a label, so on selecting any component in the JTree
, no selection color is coming.
I tried to use:
JComponent comp = (JComponent) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
comp.setOpaque(true);
if(selected)
comp.setBackground(Color.RED);
But if I return comp
, then the output of the tree is not coming as expected.
How to resolve the same?
I did not implement any Editor for the same.