简体   繁体   中英

How do i change color of Jtree based on my dynamic changing Jtree for java desktop application

Everyone, I'm making desk app with JPanel and JFrame . Here is my tree structure:

Default tree

@Root
 |-L1B  (node-1)
 |-L2A (node-2)
 |-L1A (node-3)

After this i'm reading a file (let's suppose two values: value1 and value2 ) and add leaf data.

So, I'de like to change the color like this:

@Root
 |**-L1B**  (node-1)(with green color)
    | value1(with green color)
    | value2(with green color)
 |-L2A (node-2)
 |-L1A (node-3)

value1 value might be 60s, meaning that for 60s it will in be green and then become red.

@Root
 |**-L1B**  (node-1)(with green color)
    | value1(with green red)
    | value2(with green color)
 |-L2A (node-2)
 |-L1A (node-3)

And after 60s, value2 value might be 60s more than value1 , so that for 60s it will be green and then turn red.

@Root
 |**-L1B**  (node-1)(with green color)
    | value1(with green red)
    | value2(with green color)
 |-L2A (node-2)
 |-L1A (node-3)

So, basically I want the hierarchy of running processes. When it is running, the color should be green and then it will change to another color.

What you are looking for is a custom rendered.

To do that, take your JTree and call the setCellRenderer() method passin your renderer.

A basic renderer is an inheritance of DefaultTreeCellRenderer . The method that returns the rendering is getTreeCellRendererComponent() .

Unfortunately, your question is very vague, so I can't give a more specific example, so a generic example would be:

JTree paintedTree = new JTree();
paintedTree.setCellRenderer(new DefaultTreeCellRenderer() {
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Component renderedItem = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
        if (((YourClass)value).getTime() > 60) {
            renderedItem.setBackground(Color.GREEN);
        }

        return renderedItem;
    }
});

Note that this answer is strictly from the rendering of colors' point of view. The code for determining if the process is running was simplified by (((YourClass)value).getTime() > 60) to keep the answer in focus.

Also, check this page. It might help you with your pursuit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM