首页 > 解决方案 > 如何记录随时间的运动,回放鼠标运动?

问题描述

我正在尝试记录鼠标随时间的移动并在回放时查看它们(可能是视频,可食用)。在给定特定时间时,我需要能够在坐标中检索鼠标的确切位置。例如:记录鼠标移动 20 秒。我需要在 10.6 秒时获得鼠标的位置。

随着时间的推移存储这些鼠标坐标的最佳方法是什么?播放视频的最佳方式是完整播放?

为了获取鼠标的坐标,我使用的是 Java 的官方鼠标运动监听器https://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html

public class MouseMotionEventDemo extends JPanel 
                                  implements MouseMotionListener {
    //...in initialization code:
        //Register for mouse events on blankArea and panel.
        blankArea.addMouseMotionListener(this);
        addMouseMotionListener(this);
        ...
    }

    public void mouseMoved(MouseEvent e) {
       saySomething("Mouse moved", e);
    }

    public void mouseDragged(MouseEvent e) {
       saySomething("Mouse dragged", e);
    }

    void saySomething(String eventDescription, MouseEvent e) {
        textArea.append(eventDescription 
                        + " (" + e.getX() + "," + e.getY() + ")"
                        + " detected on "
                        + e.getComponent().getClass().getName()
                        + newline);
    }
}

标签: javaswingtimeawtmousemove

解决方案


MouseEvent 类有getX()分别等方法getXOnScreen(),Y 轴也一样。

解决此问题的一种方法:创建一个包含您需要的信息的类,例如:

class SimpleCoordinate {
  private final int x;
  ...

然后在你的主程序中:

List<SimpleCoordinate> coordinatesHistory = new ArrayList<>();

在你的听众中做:

coordinatesHistory.add(new SimpleCoordinate(...))

您在课堂上存储的具体内容取决于您。可能只是“坐标”,但添加某种时间戳也可能有意义。

仔细考虑/设计/测试的关键问题:

  • 鼠标监听器有多“精细”(例如当您真正快速移动鼠标时,您会获得多少事件)
  • 该程序应该记录多长时间(如果它应该记录几天或几周的用户活动,您可能会用完内存,只需将该信息添加到内存中)

当然,或者,您可以将记录推送到某个“队列”中,并让另一个线程定期从队列中获取元素,以某种方式持久化它们。


推荐阅读