开发者

Updating JTree nodes background color at runtime

I need to change tree nodes color when business logic updates model, wait 1 second, and then change its color back.

Basically I 开发者_C百科would like to create similar thing like here Changing JList row color at runtime, but for JTree.

So I could use a similar technique,but I also wont to change ancestor nodes color, so user could see notification even if not is not expanded.

How can I do it?


First, when the business model is updated, make sure you fire the appropriate tree updated event in your tree model so the JTree will know to update.

Then you'll need to define a TreeCellRenderer that sets the color. When the business model is updated, tell your renderer which nodes to highlight.

However, the trick here is turning the color off. You can define a Thread or better yet an Executor to sleep for 1000 millis then tells the renderer to no longer highlight the nodes, then fire the tree update events again so the JTree will repaint appropriately.


Check this Highlight a node's descendants in JTree

You could easily modify it to instead highlight the parent and now you only need to plug in a solution for the timed highlighting like the solution I provided on the other thread. Highlight, timer, unset highlight.

Using SwingWorker plus maybe an Executor if the updates to the model are frequent and you want some control over the execution of the highlighting threads


It should be improved with SwingWorker to uncolor back after a time:

  class RuntimeTreeRender extends DefaultTreeCellRenderer {


    boolean specialColor = false;

    @Override
    public Color getBackgroundNonSelectionColor() {
        if(specialColor) {
            return Color.GREEN;
        } else {
            return null;
        }
    }


    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean arg2, boolean arg3, boolean arg4, int arg5, boolean arg6) {

        Component c = super.getTreeCellRendererComponent(tree, value, arg2, arg3, arg4, arg5, arg6);

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

                if(YOUR_CONDITION_ON_NODE) { // for exammple : node.getUserObject().toString().contains("a")
                    specialColor = true;
                } else {
                    specialColor = false;
                }

        return c;
    }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜