tags:

views:

2393

answers:

3

In Swing, is there a way to define mouseover text (or tool tip text) for each item in a JComboBox?

+1  A: 

I've never tried it, but you should be able to define a ListCellRenderer, and have it return a JLabel or whatever with a tool tip.

Paul Tomblin
+1  A: 

Here's little bit fixed code from an online example:

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

/**
 * @version 1.0 06/05/99
 */
public class ToolTipComboBox extends JFrame {

  /**
     * 
     */
    private static final long serialVersionUID = 2939624252688908292L;

String[] items = { "jw", "ja", "la" };

  String[] tooltips = { "Javanese ", "Japanese ", "Latin " };

  public ToolTipComboBox() {
    super("ToolTip ComboBox Example");

    JComboBox combo = new JComboBox(items);
    combo.setRenderer(new MyComboBoxRenderer());

    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(combo);
  }

  class MyComboBoxRenderer extends BasicComboBoxRenderer {
    /**
     * 
     */
    private static final long serialVersionUID = 2746090194775905713L;

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
      if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
        if (-1 < index) {
          list.setToolTipText(tooltips[index]);
        }
      } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
      }
      setFont(list.getFont());
      setText((value == null) ? "" : value.toString());
      return this;
    }
  }

  public static void main(String args[]) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}

    ToolTipComboBox frame = new ToolTipComboBox();
    frame.addWindowListener(new WindowAdapter() {
      @Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize(200, 140);
    frame.setVisible(true);
  }
}
Boris Pavlović
+2  A: 

If your combo box is not editable, use setRenderer(ListCellRenderer). If it is editable, use setEditor(ComboBoxEditor), because:

The renderer is used if the JComboBox is not editable. If it is editable, the editor is used to render and edit the selected item.

Michael Myers