【发布时间】:2015-09-16 19:36:32
【问题描述】:
我有一个扩展 JPanel 并有两个标签的 ComboBox 渲染器。 在这里我只需要在鼠标转到 iconLabel 时显示工具提示。如果鼠标在 labelItem 中,则不应显示工具提示。
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.plaf.metal.MetalIconFactory;
public class MyItemRenderer extends JPanel implements ListCellRenderer
{
private JLabel labelItem = new JLabel();
private JLabel iconLabel = new JLabel();
public MyItemRenderer() {
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 1.0;
constraints.insets = new Insets(2, 2, 2, 0);
labelItem.setOpaque(true);
labelItem.setHorizontalAlignment(JLabel.LEFT);
iconLabel.setOpaque(true);
iconLabel.setHorizontalAlignment(JLabel.RIGHT);
iconLabel.setPreferredSize(new Dimension(14, 16));
iconLabel.setMaximumSize(new Dimension(14, 16));
add(labelItem, constraints);
GridBagConstraints constraints1 = new GridBagConstraints();
constraints1.weightx = 0;
constraints1.insets = new Insets(0, 0, 0, 2);
add(iconLabel, constraints1);
setBackground(Color.LIGHT_GRAY);
}
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
String item = (String) value;
labelItem.setText(item);
// set icon
iconLabel.setIcon(MetalIconFactory.getFileChooserDetailViewIcon());
if (isSelected) {
labelItem.setBackground(Color.BLUE);
labelItem.setForeground(Color.YELLOW);
iconLabel.setBackground(Color.BLUE);
iconLabel.setForeground(Color.YELLOW);
} else {
labelItem.setForeground(Color.BLACK);
labelItem.setBackground(Color.LIGHT_GRAY);
iconLabel.setForeground(Color.BLACK);
iconLabel.setBackground(Color.LIGHT_GRAY);
}
return this;
}
}
我的工具提示只有在鼠标悬停在图标区域时才会出现。这意味着用户只需要获得他们想要的工具提示。请帮助。
【问题讨论】:
-
哇,不要问太多,首先覆盖
getToolTipText(MouseEvent),然后测试鼠标是否在目标组件内。您也可以尝试为目标组件设置工具提示 -
请将用于设置此渲染器的代码部分添加到 jcombobox。
-
为目标组件设置工具提示不起作用。如果甚至覆盖
getToolTipText(MouseEvent)我怎么能重新组织目标组件。我会很困难,因为这是一个渲染器。 -
你的源是渲染器,你的目标是带有图标的标签...
标签: java swing tooltip jcombobox