我尝试制作一些很酷的“鼠标跟踪器”..它会记录您的鼠标位置,直到您按下“跟踪”按钮,当您单击它时,它会“恢复”鼠标位置。
似乎它不处理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();
}
}
答案 0 :(得分:1)
MouseListener
添加到JFrame
或其ContentPane
,而不是JButton
- 主要原因 SwingUtilities.invokeLater()
mouseMotionListener
restore
此
for(int j = 0; j < i; j++) {
Robot r = new Robot();
到
Robot r = new Robot();
for(int j = 0; j < i; j++) {