0

我尝试制作一些很酷的“鼠标跟踪器”。它会记录您的鼠标位置,直到您按下“跟踪”按钮,当您单击它时,它会“恢复”鼠标位置。

似乎它不处理 mouseMove 方法。为什么?

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;


public class Mouse implements MouseMotionListener {
    JFrame frame = new JFrame();
    JButton move = new JButton("Track");
    Point[] points = new Point[100000];
    int i = 0;


    public Mouse() {
        // restore on track
        move.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                try {
                    Mouse.this.restore();
                } catch (InterruptedException | AWTException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        // initialize component
        frame.setPreferredSize(new Dimension(300, 300));
        frame.getContentPane().add(move);
        frame.addMouseMotionListener(this);
        frame.pack();
        frame.setVisible(true);
    }
    @Override
    public void mouseDragged(MouseEvent e) {}

    @Override
    public void mouseMoved(MouseEvent e) {
        System.out.println("Mouve move");
        if(i < 100000) {
            points[i] = e.getLocationOnScreen();
            i++;
        }
    }

    public void restore() throws InterruptedException, AWTException {
        System.out.println("Mouse restored");
        for(int j = 0; j < i; j++) {
            Robot r = new Robot();
            r.mouseMove(points[j].x, points[j].y);
            Thread.sleep(100);
        }
    }

    public static void main(String[] args) {
        Mouse s = new Mouse();
    }

}
4

1 回答 1

1
  1. 添加MouseListenerJFrame或它的ContentPane,不添加到JButton-主要原因
  2. 使用在 EDT 线程中运行 SwingSwingUtilities.invokeLater()
  3. mouseMotionListener调用时从 JFrame 中删除restore
  4. 将机器人创建置于循环之外

for(int j = 0; j < i; j++) {
    Robot r = new Robot();

Robot r = new Robot();
for(int j = 0; j < i; j++) {
于 2012-12-17T13:36:50.970 回答