I've got a JTree in which each node contains a button. I've written my own cell renderer to render the button, and I realize I have to do some special stuff to get the mouse click on the button.
My question involves the size of the displayed JTree. Over time in the program, the label on a cell's button may change. If the label gets longer, and the tree gets re-rendered, the rendering of the button gets cut off to what appears to be the initial width of the cell.
To demonstrate, I'm including a short program that creates a two node tree, where each node has a button that says "Hi". Then I render the tree by making it visible. Next, I change the label of each node to say "Goodbye". When the JTree gets re-rendered, it only renders about half of each button (the right side is cut off to the original width of the cell when the button only contained "Hi"). If anyone could provide some insight as to why it works this way, and how I can get the entire button rendered, it would be most appreciated. Thanks in advance!
In case its important, I'm running version 1.5.0_07 on a 32-but linux machine.
Originally posted by A Michaels: Never mind - I figured it out. Needed to use a DefaultTreeModel and tell the model that the node had changed, so it woudl be redrawn correctly.
If you are firing the TreeModelEvents correctly, then you should no longer need the explicit call to repaint(). The tree will repaint itself in response to the events.
btw, sometimes this exact symptom can be caused (even if the TreeModelEvents are being fired correctly) by a TreeCellRenderer that doesn't report its preferred width correctly. Your renderer doesn't have this problem, but I notice that your renderer is somewhat inefficient.
It probably doesn't matter unless your tree has a lot of nodes, but ideally your shouldn't be instantiating a Box and a JButton on every call to getTreeCellRendererComponent(). Instead do it once in your renderer's constructor and simply call setText() in getTreeCellRendererComponent().
Actually, you don't even need the Box. Just return the JButton unless you're going to put something else in it or give it a border or something.
Also, the way you have written it there's no point in calling super.getTreeCellRendererComponent(). (And once you omit that call there's no reason to extend DefaultTreeCellRenderer--just declare it to implement the TreeCellRenderer interface.)