Search code examples
javaswingjlabeljtree

JTree - JLabel update


The labels of some nodes of a JTree represent counter which increase in length after some counting. That results in an abbreviation (...). Imagine you have a tree where every node could change it's label size at any point in time.

The tree is repainted (tree.repaint()) every 100ms in a separate Thread to keep track of changing icons and changing labels which are the result of tracked events and progress in time. I tried an approach where I replaced the repaint() method with a nodeChanged() call on every tree node. The tree starts flickering.

What do I need to do, in order to update those node labels according to their new length? I am already extending a DefaultTreeCellRenderer.

 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    DefaultMutableTreeNode node;
    Object                 nodeValue;
    TestComponent          currentComponent;

    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

    node      = (DefaultMutableTreeNode) value;
    nodeValue = node.getUserObject();


    if(nodeValue instanceof TestComponent) {
        currentComponent = (TestComponent) nodeValue;
        setText(currentComponent.getLabel());

    }       
    return this;
}

What should I do within that CellRenderer inorder to "fix" the problem with "setText"?


Solution

  • The tree is repainted (tree.repaint()) every 100ms in a separate Thread, to keep track of changing icons and changing labels which are the result of tracked events and progress in time

    Wrong, the TreeModel should fire events, based on the tracked events, and the JTree will automatically update. Those changes should of course happen on the EDT, and not on a separate Thread.

    And unfortunately, the size of the JTree (and hence the size of the labels contained in it) will be limited by the parent container in which the JTree is contained. And this size will not automatically grow when the size of your JTree grows.