我有一个扩展 JPanel 的 ComboBox 渲染器并有两个标签。
在这里,我需要在鼠标移至时显示工具提示图标标签仅有的。如果鼠标在标签项不应显示工具提示。
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 event)
的方法MyItemRenderer
, 翻译MouseEvent
进入坐标空间iconLabel
(或者您想要的任何组件)。如果MouseEvent
落在组件的边界内,然后返回不同的结果
就像是...
@Override
public String getToolTipText(MouseEvent event) {
String tooltip = super.getToolTipText(event);
Point p = SwingUtilities.convertPoint(this, event.getPoint(), iconLabel);
if (iconLabel.contains(p)) {
tooltip = "I'm a banana";
}
return tooltip;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)