Java Swing - 获取鼠标悬停的对象 [英] Java Swing - Get object that the mouse hovers over

查看:490
本文介绍了Java Swing - 获取鼠标悬停的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JList,想要更改工具提示,具体取决于鼠标悬停的条目。我尝试在谷歌搜索我的问题,但没有成功。

I have a JList and want to change the tooltips, depending on the entry the mouse hovers over. I tried searching my problem on google, but had no success.

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

Basically i need to get the object i am currently hovering over.

感谢每一个帮助

推荐答案

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

In order to do that, you have to extend JList and expose the tooltip text method. Here is an example program I found sometime ago using 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);
            }
        });
    }
}

希望这有帮助。

这篇关于Java Swing - 获取鼠标悬停的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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