在Swing中,有没有办法为JComboBox中的每个项目定义鼠标悬停文本(或工具提示文本)?
有一个比ToolTipComboBox
已经给出的答案更好的方法来做到这一点.
首先,做一个自定义ListCellRenderer
:
package com.example; import javax.swing.*; import java.awt.*; import java.util.List; public class ComboboxToolTipRenderer extends DefaultListCellRenderer { Listtooltips; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JComponent comp = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (-1 < index && null != value && null != tooltips) { list.setToolTipText(tooltips.get(index)); } return comp; } public void setTooltips(List tooltips) { this.tooltips = tooltips; } }
然后像这样使用它:
JComboBox comboBox = new JComboBox(); ComboboxToolTipRenderer renderer = new ComboboxToolTipRenderer(); comboBox.setRenderer(renderer); ... //make a loop as needed comboBox.addItem(itemString); tooltips.add(tooltipString); ... renderer.setTooltips(tooltips);
我喜欢MountainX解决方案的简单性,但不喜欢缺少封装.另一种具有更多移动部件的解决方案,但它们非常简单且可重复使用.
界面:
public interface ToolTipProvider { public String getToolTip(); }
包装类:
public class ToolTipWrapper implements ToolTipProvider { final Object value; final String toolTip; public ToolTipWrapper(Object value, String toolTip) { this.value = value; this.toolTip = toolTip; } @Override public String getToolTip() { return toolTip; } @Override public String toString() { return value.toString(); } }
和MountainX的渲染器的变体:
public class ToolTipRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JComponent component = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); String tip = null; if (value instanceof ToolTipProvider) { ToolTipProvider ttp = (ToolTipProvider) value; tip = ttp.getToolTip(); } list.setToolTipText(tip); return component; } }
现在添加:
combobox.addItem(new ToolTipWrapper(itemString,tooltipString) );