【问题标题】:How to have a MouseMove event fire only if the mouse is hovered over an element for at least a specific amount of time?仅当鼠标悬停在元素上至少特定时间时,如何触发 MouseMove 事件?
【发布时间】:2014-06-27 00:15:04
【问题描述】:

当用户将鼠标指针移到JPanel 的某个区域内时,我想显示JFrame 并稍有延迟。我通过将MouseAdapter 附加到JPanel 并覆盖MouseMove 方法来显示JFrame

addMouseListener(new MouseAdapter() {
  @Override
  public void mouseMoved(MouseEvent e) {
    Point p= e.getLocationOnScreen();
    //check if Point p is within the boundaries of a rectangle.          
    //show a JFrame
  }                
});

为了获得延迟,我认为我应该通过使用sleep 来使用类似Thread 的东西,条件是如果鼠标移出边界就必须中断它,但我不确定这是最好的方法。 目前,我只看到与 JavaScript 相关的 SO 问题。在 Java 中最好的方法是什么?

【问题讨论】:

    标签: java awt mouseevent


    【解决方案1】:

    也许一个好的解决方案是使用java.util.Timer

    addMouseListener(new MouseAdapter() {
     private int delay = 1000;//1 second
     private Timer timer = null;
     private int startTime =0;
    
      @Override
      public void mouseMoved(MouseEvent e) {
        Point p= e.getLocationOnScreen();
        boolean pointInArea=false;
        //check if Point p is within the boundaries of a rectangle.          
        if(pointInArea){
            //A JFrame is queued to be shown
            if(System.currentTimeMillis()-startTime>delay){
              //A JFrame has been already shown, then show a new one
              startTime = System.currentTimeMillis();
              timer = new Timer();                    
              timer.schedule(new TimerTask(){
                  @Override
                  public void run() {
                    //LAUNCH JFrame
                  }
    
              }, delay);                     
            }
         }
         else (!pointInArea && timer != null){
            timer.cancel();
            timer = null;                        
         }
      }                
    });
    

    【讨论】:

    • 这有一些缺点。如果鼠标指针悬停在对象内,那么它将取消计时器。
    • 干得好.. 但我建议使用mouseEnteredmouseExited 事件。因为,每次移动鼠标时,都会检查移动事件是否已进入特定区域。但是如果您使用mouseEnteredmouseExited,则不会发生持续的资源消耗检查。
    • 但如果您处理 JComponent 的边界,两者都可以工作。我对JPanel 中的特定区域感兴趣,而不是整个组件区域。
    • 如果是这种情况,您的答案就是要走的路,因为您无法触发将鼠标悬停在 JPanel 的特定坐标上的事件,除非使用 mouseMoved 事件。如果您使用mouseEnteredmouseExitedevents,还有其他问题。例如,进入 JPanel 内部的组件将被视为退出 Jpanel。您必须编写更多代码来处理这些情况。所以正如我之前所说,你的路是要走的.. :) +1 ..
    【解决方案2】:

    您可以使用MouseAdapter 类中的mouseEnteredmouseExited 事件。

    您可以在mouseEntered方法上设置一个计时器,并检查对象花费的时间是否为>=mouseExited方法中指定的时间,如果是则执行操作。

    对于鼠标停留在同一点的情况,您可以使用Timer 并延迟您想要的秒数,并在mouseExited 设置一个处理程序以在指针在之前退出时停止计时器指定时间。

    【讨论】:

    • 那么鼠标停留在同一点不动的情况呢?
    • 是的,我刚刚提供了一个计时器的答案,不是摇摆的,而是实用的。
    • @mat_boy 检查我对您的回答的评论。您的答案很好,但您必须检查指针是否悬停在组件内,然后它不应该取消计时器,因为标准是如果指针在您的组件内指定的时间显示您的 jframe。
    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2011-02-23
    • 2015-09-10
    • 1970-01-01
    • 2013-02-22
    • 2013-02-27
    相关资源
    最近更新 更多