views:

1536

answers:

3

Hi,

since JTree & TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree?

Edit: (Answering my own question afterwards.)

@Zarkonnen: Thanks for the getTooltipText idea.

I found out another (maybe still a bit nicer) way with overriding DefaultTreeCellRenderer and thought to share it:

public class JTreeWithToolTips {
    private static class OwnRenderer extends DefaultTreeCellRenderer {
     @Override
     public Component getTreeCellRendererComponent(JTree tree, Object value,
       boolean sel, boolean expanded, boolean leaf, int row,
       boolean hasFocus) {
      setToolTipText("foobar" + row);
      return super.getTreeCellRendererComponent(tree, value, sel,
        expanded, leaf, row, hasFocus);
     }
    }

    public static void main(String[] args) {
     JTree tree = new JTree(new Object[] { "foo", "bar", "foobar" });
     tree.setCellRenderer(new OwnRenderer());
     ToolTipManager.sharedInstance().registerComponent(tree);

     JFrame frame = new JFrame();
     frame.getContentPane().add(tree);
     frame.pack();
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setVisible(true);
    }
}
A: 

onMouseOver ??

Dev er dev
+3  A: 

See getTooltipText on JTree. This should allow you to show tooltips depending on what in the tree is being hovered over. (Do read the docs though, you need to register the JTree with the ToolTipManager.)

Zarkonnen
A: 

yeah... you can use onMouseMoved and then use a mthod (I don't remember the name) that tells you in which node you are over... if you get null, obviously then u are not over a node...

Agustin