importjava.awt.*;importjava.awt.event.InputEvent;publicclassMousePositionTracker{publicstaticvoidmain(String[] args)throwsAWTException,InterruptedException{Robot robot =newRobot();while(true){// Get the current mouse positionPoint mousePosition =MouseInfo.getPointerInfo().getLocation();int x =(int) mousePosition.getX();int y =(int) mousePosition.getY();// Print the coordinates to the consoleSystem.out.println("Mouse position: ("+ x +", "+ y +")");// Wait for 1 secondThread.sleep(1000);}}}
对电脑指定坐标进行点击
importjava.awt.*;importjava.awt.event.InputEvent;publicclassScreenClicker{publicstaticvoidmain(String[] args)throwsAWTException{Robot robot =newRobot();int x =673;int y =723;for(int i =0; i <20; i++){
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);// Press the left mouse button
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);// Release the left mouse buttontry{Thread.sleep(1000);// Wait for 1 second between clicks}catch(InterruptedException e){
e.printStackTrace();}}System.out.println("Clicked on location ("+ x +", "+ y +")");}}
用户按下指定按键对程序做出终止(注意英文输入法才可以识别)
importjavax.swing.*;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;publicclassKeyPressDetectorimplementsKeyListener{privateJFrame frame;publicKeyPressDetector(){// Create a JFrame window
frame =newJFrame("Key Press Detector");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);// Register the KeyListener to the JFrame window
frame.addKeyListener(this);}@OverridepublicvoidkeyTyped(KeyEvent e){// keyTyped event is triggered when a character is typed// This method is not used in this example, but it's required to implement the KeyListener interface}@OverridepublicvoidkeyPressed(KeyEvent e){// keyPressed event is triggered when a key is pressedif(e.getKeyCode()==KeyEvent.VK_Q){System.out.println("Exiting the program.");System.exit(0);// Exit the program}}@OverridepublicvoidkeyReleased(KeyEvent e){// keyReleased event is triggered when a key is released// This method is not used in this example, but it's required to implement the KeyListener interface}publicstaticvoidmain(String[] args){// Create an instance of KeyPressDetector to start the programnewKeyPressDetector();}}