如何在jframe中找到滑动方向

How to find direction of swipe in jframe

我正在开发 运行 在触摸屏 linux 平板电脑上的 swing 应用程序。我想实现一个模块,我可以在其中找到用户在屏幕上滑动手指的方向。我正在使用 MouseMotionListener 来查找鼠标的位置。但现在我很困惑如何才能找到鼠标移动的确切方向。我只对在 jframe 上找到向上和向下运动感兴趣。有人可以给我一些想法吗

I am using MouseMotionListener to find the position of the mouse.

我猜您需要跟踪两个 MouseEvents:

  1. 上一个事件(或者可能是启动滑动的 mousePressed 事件?)
  2. 当前事件。

这样您就可以访问每个事件产生的两个点。

然后您使用基础数学比较这两点。如果当前 y 值较大,则向下滑动,否则向上滑动。

我想添加这个示例代码来说明@camickr 的回答,因为它可能会有所帮助——因为它作为编辑被拒绝了,而且我没有足够的积分来添加评论,这里是:

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class DragDirectionDemo {

    public static void main(String[] args) {

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

                JFrame frame = new JFrame("Drag Direction Demo");
                frame.setSize(500, 500);
                frame.setVisible(true);
                frame.addMouseListener(new MouseListener() {

                    float lastY = 0;

                    public void mouseReleased(MouseEvent e) {
                        System.out.println("Mouse released at " + e.getY());
                        if (e.getY() < lastY) {
                            System.out.println("Upward swipe");
                        } else if (e.getY() > lastY) {
                            System.out.println("Downward swipe");
                        } else {
                            System.out.println("No movement");
                        }
                        ;
                    }

                    public void mousePressed(MouseEvent e) {
                        System.out.println("Mouse clicked at " + e.getY());
                        lastY = e.getY();
                    }

                    public void mouseEntered(MouseEvent e) {
                    }

                    public void mouseExited(MouseEvent e) {
                    }

                    public void mouseClicked(MouseEvent e) {
                    }
                });
            }
        });
    }
}

这只是一个玩具示例,说明了@camickr 的回答中解释的方法:在运动开始时跟踪 y 坐标(在我的示例中,鼠标按钮被按下);然后,在运动结束时将其与 y 坐标进行比较(在我的示例中,鼠标按钮已释放 - 可能需要调整触摸,我不知道)。

观察控制台输出,指示拾取的动作是什么。祝你好运!