简体   繁体   English

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

[英]Why isn't my program handles mouse motion? (Java)

I try to make some cool "Mouse tracker" .. It records your mouse positions until you press the "Track" button, and when you click it , It "restores" the mouse position. 我尝试制作一些很酷的“鼠标跟踪器”。它会记录您的鼠标位置,直到您按下“跟踪”按钮为止,然后单击它,它会“恢复”鼠标位置。

It's seems it doesn't handle the mouseMove method. 似乎它无法处理mouseMove方法。 why? 为什么?

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. add MouseListener to JFrame or its ContentPane , not to JButton - main reason MouseListener添加到JFrame或其ContentPane而不是JButton 主要原因
  2. Run Swing in EDT thread using SwingUtilities.invokeLater() 使用SwingUtilities.invokeLater()在EDT线程中运行Swing
  3. Remove mouseMotionListener from JFrame when you call restore 调用restore时,从JFrame中删除mouseMotionListener
  4. Put Robot creation outside of loop 将机器人创建置于循环之外

This 这个

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM