Tooltip for items in a jcombobox?

I need to enable a tooltip for each individual item in a jcombobox. In the answer to question 10065772 the recomendation was to edit the treeCombo.java in the swingSet example. Can anybody please help me and explain exactly what i need to change to make it work, i have tried to add setToolTipText in the getCellRendererComponent but nothing happens...

Thanks
Mattias
marbergAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

marbergAuthor Commented:
Adjusted points to 100
0
heyhey_Commented:
1. can you post your code so that we can work on it.
2. what's your OS / JDK version / Swing version ?
0
marbergAuthor Commented:
OS Win95/98, JDK 1.2, Swing ??

The code...
Please observe that I only use this code for test purpose. If I get the tooltip facility to work properly I will rewrite the code...

public class TreeCombo extends JComboBox {
    static final int OFFSET = 16;

    public TreeCombo(TreeModel aTreeModel) {
        super();
        setModel(new TreeToListModel(aTreeModel));
        setRenderer(new ListEntryRenderer());
    }

    class TreeToListModel extends AbstractListModel implements ComboBoxModel,TreeModelListener {
        TreeModel source;
        boolean invalid = true;
        Object currentValue;
        Vector cache = new Vector();

        public TreeToListModel(TreeModel aTreeModel) {
            source = aTreeModel;
            aTreeModel.addTreeModelListener(this);
            setRenderer(new ListEntryRenderer());
        }

        public void setSelectedItem(Object anObject) {
            currentValue = anObject;
            fireContentsChanged(this, -1, -1);
        }

        public Object getSelectedItem() {
            return currentValue;
        }

        public int getSize() {
            validate();
            return cache.size();
        }

        public Object getElementAt(int index) {
            return cache.elementAt(index);
        }

        public void treeNodesChanged(TreeModelEvent e) {
            invalid = true;
        }

        public void treeNodesInserted(TreeModelEvent e) {
            invalid = true;
        }

        public void treeNodesRemoved(TreeModelEvent e) {
            invalid = true;
        }

        public void treeStructureChanged(TreeModelEvent e) {
            invalid = true;
        }

        void validate() {
            if(invalid) {
                cache = new Vector();
                cacheTree(source.getRoot(),0);
                if(cache.size() > 0)
                    currentValue = cache.elementAt(0);
                invalid = false;            
                fireContentsChanged(this, 0, 0);
            }
        }

        void cacheTree(Object anObject,int level) {
            if(source.isLeaf(anObject))
                addListEntry(anObject,level,false);
            else {
                int c = source.getChildCount(anObject);
                int i;
                Object child;

                addListEntry(anObject,level,true);
                level++;

                for(i=0;i<c;i++) {
                    child = source.getChild(anObject,i);
                    cacheTree(child,level);
                }

                level--;
            }
        }

        void addListEntry(Object anObject,int level,boolean isNode) {
            cache.addElement(new ListEntry(anObject,level,isNode));
        }
    }

    class ListEntry {
        Object object;
        int    level;
        boolean isNode;

        public ListEntry(Object anObject,int aLevel,boolean isNode) {
            object = anObject;
            level = aLevel;
            this.isNode = isNode;
        }

        public Object object() {
            return object;
        }

        public int level() {
            return level;
        }

        public boolean isNode() {
            return isNode;
        }

        public String toString() {
          return object.toString();
        }
    }

    static Border emptyBorder = new EmptyBorder(0,0,0,0);

    class ListEntryRenderer extends JLabel implements ListCellRenderer  {
        ImageIcon leafIcon = SwingSet.sharedInstance().loadImageIcon("images/document.gif","Document");
        ImageIcon nodeIcon = SwingSet.sharedInstance().loadImageIcon("images/folder.gif","Folder");

        public ListEntryRenderer() {
            setOpaque(true);
        }

        public Component getListCellRendererComponent(JList listbox, Object value, int index, boolean isSelected, boolean cellHasFocus)      {
            ListEntry listEntry = (ListEntry)value;
            if(listEntry != null) {
                Border border;
                setText(listEntry.object().toString());
                        setIcon( listEntry.isNode() ? nodeIcon : leafIcon );
                setToolTipText(listEntry.object().toString());
                if(index != -1)
                    border = new EmptyBorder(0, OFFSET * listEntry.level(), 0, 0);
                else
                    border = emptyBorder;

                if(UIManager.getLookAndFeel().getName().equals("CDE/Motif")) {
                    if(index == -1 )
                        setOpaque(false);
                    else
                        setOpaque(true);
                } else
                    setOpaque(true);

                        setBorder(border);
                if (isSelected) {
                    setBackground(UIManager.getColor("ComboBox.selectionBackground"));
                    setForeground(UIManager.getColor("ComboBox.selectionForeground"));
                } else {
                    setBackground(UIManager.getColor("ComboBox.background"));
                    setForeground(UIManager.getColor("ComboBox.foreground"));
                }
            } else {
                setText("");
            }
          return this;
      }
    }
}
0
JodCommented:
The basic principle is that you have to call setToolTipText(String), defined in JComponent.

For components that do not have builtin tool tip support, you may create a JToolTip instance, set its text with setTipText(String), and bind it to a component with setComponent(JComponent).

To create your own custom tool tips, you may override the createToolTip() method in JComponent.

In your case, some example code from sun is:

  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  import javax.swing.plaf.basic.*;
  public class ToolTipComboBoxExample extends JFrame {
    String[] items    = {"A"      ,"a"      ,"1"      };
    String[] tooltips = {"ABCDEFG","abcdefg","1234567"};
    public ToolTipComboBoxExample() {
      super("Block ComboBox Example");  
      JComboBox combo = new JComboBox(items);
      combo.setRenderer(new MyComboBoxRenderer());
      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(combo);
    }
    class MyComboBoxRenderer extends BasicComboBoxRenderer {

      public Component getListCellRendererComponent( JList list,  
           Object value, int index, boolean isSelected, boolean cellHasFocus) {
        if (isSelected) {
          setBackground(list.getSelectionBackground());
          setForeground(list.getSelectionForeground());      

          list.setToolTipText(tooltips[index]);          // here

         } else {
          setBackground(list.getBackground());
          setForeground(list.getForeground());
        }       
        setFont(list.getFont());
        setText((value == null) ? "" : value.toString());      
        return this;
      }  

    }
    public static void main (String args[]) {
      ToolTipComboBoxExample frame = new ToolTipComboBoxExample();
      frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) { System.exit(0); }
      });
      frame.setSize(200, 150);
      frame.setVisible(true);
    }
  }

Basically, this sets up an array of tooltips that are assigned individually to each item in the combobox using this code here:

      public Component getListCellRendererComponent( JList list,  
           Object value, int index, boolean isSelected, boolean cellHasFocus) {
        if (isSelected) {
          setBackground(list.getSelectionBackground());
          setForeground(list.getSelectionForeground());      

          list.setToolTipText(tooltips[index]);          // here

         } else {
          setBackground(list.getBackground());
          setForeground(list.getForeground());
        }       
        setFont(list.getFont());
        setText((value == null) ? "" : value.toString());      
        return this;
      }

NOTE: You should check the index to make sure it is valid before using it here as well, by the way.

You don't have to use an array here, but the principle is to use some method that will allow you to retrieve different text for each item based on the index passed into the getListCellRendererComponent method.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
marbergAuthor Commented:
Thanks alot!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.