为什么我的程序不能处理鼠标移动? (JAVA)

时间:2012-12-17 13:15:19

标签: java events mouseevent

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

似乎它不处理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();
    }

}

1 个答案:

答案 0 :(得分:1)

  1. MouseListener添加到JFrame或其ContentPane,而不是JButton - 主要原因
  2. 使用SwingUtilities.invokeLater()
  3. 在EDT主题中运行Swing
  4. 在致电mouseMotionListener
  5. 时,从JFrame中移除restore
  6. 将机器人创建置于循环之外
  7. for(int j = 0; j < i; j++) {
        Robot r = new Robot();
    

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