JList with tooltip text in DafaultListModel

て烟熏妆下的殇ゞ 提交于 2019-12-08 13:35:00

问题


I have a JList and each item of the JList has a distinct display text and tooltip text. I would like to use 'DefaultListModel' for the JList. My question is that is it possible to somehow save the tooltip text when added an item to the DefaultListModel.

Thanks.


回答1:


You can override the getToolTipText(...) method to provide your custom tool tip.

For example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ListToolTip extends JFrame
{
    public ListToolTip()
    {
        DefaultListModel model = new DefaultListModel();
        model.addElement("one");
        model.addElement("two");
        model.addElement("three");
        model.addElement("four");
        model.addElement("five");
        model.addElement("six");
        model.addElement("seven");
        model.addElement("eight");
        model.addElement("nine");
        model.addElement("ten");

        JList list = new JList( model )
        {
            public String getToolTipText( MouseEvent e )
            {
                int row = locationToIndex( e.getPoint() );
                Object o = getModel().getElementAt(row);
                return o.toString();
            }

            public Point getToolTipLocation(MouseEvent e)
            {
                int row = locationToIndex( e.getPoint() );
                Rectangle r = getCellBounds(row, row);
                return new Point(r.width, r.y);
            }
        };

        JScrollPane scrollPane = new JScrollPane( list );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        ListToolTip frame = new ListToolTip();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(400, 100);
        frame.setVisible( true );
    }
}

Overriding getToolTipLocation(...) is not necessary.

Edit:

I want to save the custom text in the model

Then you would need to save a custom object in the model that contains the value displayed in the list and the text for the tooltip.

Check out ComboBox With Hidden Data for an example of creating an object using this approach.



来源:https://stackoverflow.com/questions/44161110/jlist-with-tooltip-text-in-dafaultlistmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!