JComboBox Tooltip
Posted by blogmeister on
July 3, 2011
You wonder why there may be a need to have a tooltip inside a JComboBox. What if your item is very long like the image shown below?
This where tooltips come in handy unless you plan to have your JComboBox display items in multi-line if they are very long but that won’t look good. A tooltip is the best solution and the way to go about this is to assign a renderer to the JComboBox that does this.
This class does the trick. You only need to instantiate this and assign it to the JComboBox by calling the setRenderer() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class ComboBoxToolTipRenderer extends BasicComboBoxRenderer { @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(list.getSelectedValue().toString()); } } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setFont(list.getFont()); setText((value == null) ? "" : value.toString()); return this; } } |









