Billie
Billie

Reputation: 9146

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. 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();
    }

}

Upvotes: 0

Views: 149

Answers (1)

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

  1. add MouseListener to JFrame or its ContentPane, not to JButton - main reason
  2. Run Swing in EDT thread using SwingUtilities.invokeLater()
  3. Remove mouseMotionListener from JFrame when you call restore
  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++) {

Upvotes: 1

Related Questions