I am using a JTree
, which is using a DefaultTreeModel
. This tree model has some nodes inside, and when I click on a node, I get the information of the node and I change the background color to show that this node is selected.
It is possible to call the tree to clear the selection when I click on any place out of the tree? By clearing the selection I will be able to change the background color again, but I don't know how or where to use the clearSelection()
method of the tree when I click out of the tree.
Here is the code I am using:
The example:
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class JTreeSelectDeselect {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JTree tree = new JTree();
tree.setCellRenderer(new DeselectTreeCellRenderer());
panel.add(tree, BorderLayout.LINE_START);
panel.add(new JScrollPane(new JTextArea(10, 30)));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
class DeselectTreeCellRenderer extends DefaultTreeCellRenderer {
@Override
public Color getBackgroundSelectionColor() {
return new Color(86, 92, 160);
}
@Override
public Color getBackground() {
return (null);
}
@Override
public Color getBackgroundNonSelectionColor() {
return new Color(23, 27, 36);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
setForeground(new Color(225, 225, 221, 255));
setOpaque(false);
return this;
}
}
I am showing here how I create the nodes and add it to the tree using a tree model and how I set my custom TreeCellRenderer
.
In the cell renderer I paint the selected node with a specific color, and if the node is deselected, I paint it using another color. When I change the selection of the nodes, their background is painting correctly, but when I click outside the tree, the selected node is not deselected, so it is not painted with the specific color established in the cell renderer.
There is a way to deselect the node when I click outside the tree?
And just if someone knows, there is a way to change some of the leafs by check boxes from the TreeCellRenderer
? To have some children as labels and some others as check boxes. Because when I try to add check boxes it says (as I expected) that check boxes are not DefaultMutableTreeNode
objects and I can't add them to the tree model.