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

醉酒当歌 提交于 2020-07-31 05:50:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33919962/how-do-i-change-color-of-jtree-based-on-my-dynamic-changing-jtree-for-java-deskt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!