?
Solved

Tooltip for items in a jcombobox?

Posted on 1999-12-01
5
Medium Priority
?
1,471 Views
Last Modified: 2011-09-20
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
0
Comment
Question by:marberg
  • 3
5 Comments
 

Author Comment

by:marberg
ID: 2245967
Adjusted points to 100
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 2246170
1. can you post your code so that we can work on it.
2. what's your OS / JDK version / Swing version ?
0
 

Author Comment

by:marberg
ID: 2246278
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
 
LVL 5

Accepted Solution

by:
Jod earned 400 total points
ID: 2247151
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
 

Author Comment

by:marberg
ID: 2248938
Thanks alot!
0

Featured Post

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses
Course of the Month5 days, 3 hours left to enroll

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question