Repainting a JTree

R

This is just going to be a quick little post about how to get around redraw issues when you need to repaint a JTree in Java. Sometimes when you force a repaint with a JTree, the nodes are rendered with a “…” at the end of the node text (see picture below). This happens when the text that needs to be rendered is outside the bounds of the Node object being painted. This really only happens when the text that needs to be rendered has changed between the last rendered state and the new repaint.

I’ve run into this issue a number of times due to all my various JTree hacking in projects like CogZ, ZoomableJTrees, and now again in my Change Analysis plugin.

Typically to force a JTree to repaint, you might do something like this:

myTree.invalidate();
myTree.validate();
myTree.repaint();

This code will force a re-rendering of the JTree object, but if the node sizes needed to be re-calculated, the tree will end up displaying as in my screenshot above. So, my trick to get around this issue is to actually change the JTree row size before I call the repaint, this will force the JTree to recalculate all the node size bounds.

// call setRowHeight to force the sizes to recalculate
myTree.setRowHeight(DEFAULT_ROW_HEIGHT);
// repaint this puppy
myTree.repaint();

It’s a bit weird, but it works :-).

About the author

Sean Falconer

8 Comments

By Sean Falconer

Sean Falconer

Get in touch

I write about programming, developer relations, technology, startup life, occasionally Survivor, and really anything that interests me.