swing中重写JPanel的createToolTip

swing中重写JPanel的createToolTip

本文介绍了在Java swing中重写JPanel的createToolTip()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ListCellRenderer扩展了JPanel.现在,我尝试覆盖其createToolTip().但是似乎方法没有被重写.可能是什么原因?

I have a ListCellRenderer which extends JPanel. Now I try to override its createToolTip(). But it seems like method is not getting overridden. What could be the reason?

我的代码:

public class MyRender extends JPanel implements ListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        if (value != null) {
            removeAll();

            // -- add data to JPanel.

            setToolTipText("hi");
            return this;
        }
        return null;
    }

    @Override
    public JToolTip createToolTip() {
        System.out.println("Success");
        return new MyToolTip();
    }
}

它甚至不打印成功".

推荐答案

我猜想永远不会调用此方法,因为ListCellRenderer充当"橡胶印章",因此仅在重新绘制时存在,并且永远不会添加到任何容器中,尤其是不会添加到分配给它的JList.

I guess this method is never called because the ListCellRenderer acts as a "rubber stamp", hence it exists only during repaint, and is never added to any container, in particular not the JList it is assigned to.

因此,工具提示始终是由JList本身创建的,而不是由ListCellRenderer创建的.

Thus, the tooltip is always created by the JList itself, never the ListCellRenderer.

如果要为列表中的每个项目提供特殊的工具提示,则有几种方法,最简单(但可能不是最好的)的方法可能是将JList子类化并覆盖getToolTipText(MouseEvent e).该方法接收到要获取工具提示的鼠标坐标,您必须使用locationToIndex()将其转换为鼠标所在项目的索引.

If you want to have a special tooltip for every item in your list, then there are several ways, the easiest (but maybe not the nicest) is probably to subclass JList and override getToolTipText(MouseEvent e). That method received the mouse coordinates for which to get the tooltip, you'll have to convert them to the index of the item over which the mouse is, by using locationToIndex().

这篇关于在Java swing中重写JPanel的createToolTip()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:31