如何在Java中延迟MouseOver?

时间:2011-11-18 19:11:16

标签: java swing timer mouseover wait

我有一个简短的问题,希望有人可以帮助我。

请查看以下代码段:

public void mouseEntered(MouseEvent e){
   //wait 2 seconds.
   //if no other mouseEntered-event occurs, execute the following line
   //otherwise restart, counting the 2 seconds.
   foo();
}

有人可以帮我解决这个问题吗?我想实现像ToolTip这样的行为:你用鼠标进入一个区域。如果您的鼠标停留在该位置,请执行某些操作。

2 个答案:

答案 0 :(得分:6)

mouseEntered()方法中以{2}的方式启动Timer,该方法会调用您想要执行的操作。

设置一个新的处理程序(mouseExited()),如果计时器没有关闭,它将停止计时器。

基本上,如果未调用mouseExited(),您就知道鼠标仍然存在。计时器将在两秒钟内完成您想要的操作或在鼠标退出时取消。

答案 1 :(得分:1)

虽然@Brian Roach提供的答案是正确的,但还有另一种(也更简洁)的方式来实现这一目标。也就是说,使用ToolTipManager

示例:

import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;

public final class ToolTipDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                ToolTipManager.sharedInstance().setInitialDelay(2000);
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.add(new JToolTipButton());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class JToolTipButton extends JButton{
        private static final long serialVersionUID = -5193366265809801639L;

        protected JToolTipButton(){
            super("I can haz tooltip?");
            setToolTipText("Hey man, get off me!");
        }
    }

}

通过调用setInitialDelay,我将经理等待显示工具提示的时间从750毫秒更改为2000毫秒。

注意 - 虽然我不确定,但我认为这可能会改变所有组件(guess I was right)的延迟,这可能不是你想要的......但它仍然值得一提。