0

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();
 }
}
asked Dec 17, 2012 at 13:15
1
  • so what actually happens after you press the button? what is the value of i, is it > 0? Create Robot outside of for loop. Commented Dec 17, 2012 at 13:22

1 Answer 1

1
  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++) {
answered Dec 17, 2012 at 13:36
Sign up to request clarification or add additional context in comments.

1 Comment

@user1798362, frame.removeMouseMotionListener(this); docs.oracle.com/javase/1.4.2/docs/api/java/awt/…

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.