在DafaultListModel中带有工具提示文本的JList [英] JList with tooltip text in DafaultListModel

查看:124
本文介绍了在DafaultListModel中带有工具提示文本的JList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JList,JList的每个项目都有不同的显示文本和工具提示文本.我想为JList使用"DefaultListModel".我的问题是,在将项目添加到DefaultListModel时是否可以以某种方式保存工具提示文本.

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.

谢谢.

推荐答案

您可以覆盖getToolTipText(...)方法以提供自定义工具提示.

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

例如:

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 );
    }
}

不必覆盖getToolTipLocation(...).

我想将自定义文本保存在模型中

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.

这篇关于在DafaultListModel中带有工具提示文本的JList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆