加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Swing – 获取鼠标悬停的对象

发布时间:2020-12-15 04:18:00 所属栏目:Java 来源:网络整理
导读:我有一个JList,想要更改工具提示,具体取决于鼠标悬停的条目.我尝试在谷歌搜索我的问题,但没有成功. 基本上我需要得到我正在徘徊的对象. 感谢每一位帮助 解决方法 为此,您必须扩展JList并公开工具提示文本方法.以下是我之前使用Google发现的示例程序: import
我有一个JList,想要更改工具提示,具体取决于鼠标悬停的条目.我尝试在谷歌搜索我的问题,但没有成功.

基本上我需要得到我正在徘徊的对象.

感谢每一位帮助

解决方法

为此,您必须扩展JList并公开工具提示文本方法.以下是我之前使用Google发现的示例程序:

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

// Custom class to extend our JList and expose tooltip functionality.
class MyList extends JList {

    public MyList() {
        super();

        // Attach a mouse motion adapter to let us know the mouse is over an item and to show the tip.
        addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseMoved(MouseEvent e) {
                MyList theList = (MyList) e.getSource();
                ListModel model = theList.getModel();
                int index = theList.locationToIndex(e.getPoint());
                if (index > -1) {
                    theList.setToolTipText(null);
                    String text = (String) model.getElementAt(index);
                    theList.setToolTipText(text);
                }
            }
        });
    }

    // Expose the getToolTipText event of our JList
    public String getToolTipText(MouseEvent e) {
        return super.getToolTipText();
    }
}

public class TestJList extends JFrame {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TestJList myTest = new TestJList();
                myTest.setTitle("Example JList");
                myTest.setSize(300,300);
                myTest.setDefaultCloSEOperation(EXIT_ON_CLOSE);

                MyList list = new MyList();

                // Create our model and add some items.
                DefaultListModel model = new DefaultListModel();

                model.addElement("one");
                model.addElement("two");
                model.addElement("three");
                model.addElement("four");

                // Set the model for our list
                list.setModel(model);

                ToolTipManager.sharedInstance().registerComponent(list);

                // Add our custom list and show the form.
                MyTest.add(list);
                MyTest.setVisible(true);
            }
        });
    }
}

希望这可以帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读