How to change style (color, font) of a single JTree node
Asked Answered
C

2

5

I have two JTree in two panels in a JFrame. I want to change the style(color and font) of nodes on drag and drop from one tree to the other.Please provide me a way to change the color of a JTree node permanently.

enter image description here

Cellini answered 11/4, 2012 at 18:31 Comment(0)
A
13

To start, you will need to have a data object that can handle style and color. You could subclass DefaultMutableTreeNode and add these data items with getts and setters

Then you'd need to create a custom TreeCellRenderer. I recommend extending DefaultTreeCellRenderer, and in the overridden handler, checking for your custom class, and modifying the JLabel output to use the Font and Color if these values are set

Acrobatics answered 11/4, 2012 at 18:37 Comment(4)
No, it would be helpful if YOU provided some code. Then we could help you fix whatever was wrong with itAcrobatics
+1 for TreeCellRenderer. @soumitrachatterjee: A related example may be found here; adding setForeground(Color.blue) may help you create an sscce.Bunche
user1291492 no luck...please help me a bit....i am trying with your example...i have two DefaultMutableTreeNode objects :DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path .getLastPathComponent(); DefaultMutableTreeNode node = new DefaultMutableTreeNode(element);Cellini
i want to color this parent and node object....in which method i will pass these two as argument.???Please Help...Cellini
B
9

Create your own CellRenderer. To give the appropriate behaviour to your MyTreeCellRenderer, you will have to extend DefaultTreeCellRenderer and override the getTreeCellRendererComponent method.

public class MyTreeCellRenderer extends DefaultTreeCellRenderer {

    @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);

        // Assuming you have a tree of Strings
        String node = (String) ((DefaultMutableTreeNode) value).getUserObject();

        // If the node is a leaf and ends with "xxx"
        if (leaf && node.endsWith("xxx")) {
            // Paint the node in blue
            setForeground(new Color(13, 57 ,115));
        }

        return this;
    }
}

Finally, say your tree is called myTree, set your CellRenderer to it:

myTree.setCellRenderer(new MyTreeCellRenderer());
Besnard answered 17/12, 2014 at 10:17 Comment(2)
This runs perfectly, great piece of code! But, what if want to change also the background color of the tree? When in the MyTreeCellRenderer, under the line setForeground(new Color(13, 57 ,115));, I write setBackground(Color.YELLOW);, the background of the tree does not turn to yellow..Chausses
See if #16500914 helpsFibrovascular

© 2022 - 2024 — McMap. All rights reserved.