如何在Java中延迟MouseOver?

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

请查看以下代码段:

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这样的行为:你用鼠标进入一个区域。 如果您的鼠标停留在该位置,请执行某些操作。

mouseEntered()方法中启动一个延迟2秒的计时器 ,该方法调用您想要执行的任何操作。

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

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

虽然@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 ,我已经将管理器等待显示工具提示的时间从750ms更改为2000ms。

注意 – 虽然我不确定,但我认为这可能会改变所有组件的延迟( 我猜对了 ),这可能不是你想要的……但它仍然值得一提。