Java JTree set tooltip text for tree node

Description

Java JTree set tooltip text for tree node

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.ToolTipManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;

public class Main {
   public static void main(String[] args) {
      DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      rootNode.add(a);/*from   w  w  w. j  a v  a 2 s . com*/

      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("2");
      a.add(a2);

      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      rootNode.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("1");
      b.add(b1);

      JTree tree = new JTree(rootNode);
      ToolTipManager.sharedInstance().registerComponent(tree);

      Icon leafIcon = new SquareIcon();
      tree.setCellRenderer(new MyRenderer(leafIcon));


      tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new JScrollPane(tree));
      f.setSize(250, 250);
      f.setVisible(true);
   }
}

class MyRenderer extends DefaultTreeCellRenderer {
   Icon tutorialIcon;

   public MyRenderer(Icon icon) {
      tutorialIcon = icon;
   }
   public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf,
         int row, boolean hasFocus) {
      super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
      setIcon(tutorialIcon);
      super.setToolTipText("test from demo2s.com");
      return this;
   }
}

class SquareIcon implements Icon {
   private static final int SIZE = 10;

   public void paintIcon(Component c, Graphics g, int x, int y) {
      if (c.isEnabled()) {
         g.setColor(Color.RED);
      } else {
         g.setColor(Color.GRAY);
      }

      g.fillRect(x, y, SIZE, SIZE);
   }

   public int getIconWidth() {
      return SIZE;
   }

   public int getIconHeight() {
      return SIZE;
   }
}



PreviousNext

Related