Search code examples
javaswingtooltipjlistdefaultlistmodel

JList with tooltip text in DafaultListModel


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.


Solution

  • 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.