I saw a lot of postings & questions regarding the coloring issue of the JTree
. But I did not find any solution for my specific problem.
I want to select a node and highlight it in case of clicking one my self-made activate button and undo the highlighting by clicking the deactivate button.
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Motor testing");
root.add(new DefaultMutableTreeNode("Option 1000 RPM"));
root.add(new DefaultMutableTreeNode("Option 2000 RPM"));
//--------------- activate button
JButton btnNewButton = new JButton("Activate");
btnNewButton.addActionListener(new ActionListener() {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
//.... essential rest
}
I tried many things, like modifying the DefaultTreeCellRenderer
. But I was not able to solve the problem.
Edit:
I tried following lines:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
((MyTreeCellRenderer) tree.getCellRenderer()).activateLeaf = true;
}
}
and:
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
public boolean activateLeaf = false;
@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);
if(activateLeaf)
setForeground(Color.GREEN);
return this;
}
But the nodes turn only green if i change the selection after I pressed the activate button. And if I reset the flag immediatley after it has been set, nothing happens. I want a solution which is able to modify specific nodes, and which is able to run recursivley through every parent node.
I also want to be able to change multiple selections not only one.