监听鼠标和键盘的操作,存入集合的java代码
时间: 2024-05-11 17:20:16 浏览: 67
Java中使用Jedis操作Redis的示例代码
以下是Java代码示例,展示如何监听鼠标和键盘的操作,并将其存入集合中:
```java
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
public class MouseAndKeyboardListener implements MouseListener, KeyListener {
private Robot robot;
private List<String> actions;
public MouseAndKeyboardListener() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
actions = new ArrayList<>();
}
@Override
public void mouseClicked(MouseEvent e) {
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
actions.add("Mouse clicked at (" + mousePoint.x + ", " + mousePoint.y + ")");
}
@Override
public void mousePressed(MouseEvent e) {
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
actions.add("Mouse pressed at (" + mousePoint.x + ", " + mousePoint.y + ")");
}
@Override
public void mouseReleased(MouseEvent e) {
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
actions.add("Mouse released at (" + mousePoint.x + ", " + mousePoint.y + ")");
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
actions.add("Key pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
@Override
public void keyReleased(KeyEvent e) {}
public List<String> getActions() {
return actions;
}
}
```
在这个示例中,我们使用了Java的AWT库中的Robot类来模拟鼠标和键盘的操作。我们实现了MouseListener和KeyListener接口,以便监听这些操作。每次操作发生时,我们都会将其转换为一个字符串,并将其存入一个List集合中。最后,我们可以通过调用`getActions()`方法来获取所有已记录的操作。
阅读全文