如何在Java Swing中获取鼠标悬停事件

9
我有一个包含多个组件的JPanel,例如几个JLabelsJTextBoxesJComboBoxesJCheckBoxes
我想在用户悬停在这些组件上3秒钟后显示弹出式帮助窗口。
目前,我为其中一个组件添加了MouseListener,它确实显示所需的弹出式帮助。但是,我无法在3秒延迟后实现此效果。只要用户将鼠标移动到该组件的区域,弹出式窗口就会立即显示。这非常烦人,使得这些组件几乎无法使用。我尝试使用MouseMotionListener并将以下代码放在mouseMoved(MouseEvent e)方法中。效果相同。
您有什么建议吗?如何实现鼠标悬停效果——仅在3秒延迟后显示弹出窗口?
示例代码:(鼠标进入方法)
private JTextField _textHost = new JTextField();

this._textHost().addMouseListener(this);

@Override
public void mouseEntered(MouseEvent e) {

    if(e.getSource() == this._textHost())
    {
        int reply = JOptionPane.showConfirmDialog(this, "Do you want to see the related help document?", "Show Help?", JOptionPane.YES_NO_OPTION);
        if(reply == JOptionPane.YES_OPTION)
        {
            //Opens a browser with appropriate link. 
            this.get_configPanel().get_GUIApp().openBrowser("http://google.com");
        }
    }

}

1
你看过工具提示了吗? - trashgod
@trashgod,使用 ToolTips,我只能设置字符串。但是我想显示确认对话框,并根据响应打开浏览器以获取帮助(与我在上面的 mouseEntered 方法中展示的代码相同)。有没有办法通过 ToolTip 实现确认对话框? - TinyStrides
1个回答

8

mouseEntered() 中使用 Timer。这里有一个可行的示例:

public class Test {

    private JFrame frame;


    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Test test = new Test();
                test.createUI();
            }
        });
    }

    private void createUI() {
        frame = new JFrame();
        JLabel label = new JLabel("Test");
        label.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseEntered(MouseEvent me) {
                startTimer();
            }
        });

        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }

    private void startTimer() {
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        JOptionPane.showMessageDialog(frame, "Test");
                    }
                });
            }
        };

        Timer timer = new Timer(true);
        timer.schedule(task, 3000);
    }
}

1
离开鼠标后,猜测计时器应该停止。 - StanislavL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接