利用java robot实现模拟键盘事件和截屏

    xiaoxiao2026-10-03  6

    利用java robot模拟键盘事件,并实现截屏的。程序比较简单: 要得到一个robot对象,首先应该得到一个GraphicsEnvironment对象,然后得到default screen设备: GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice screen = environment.getDefaultScreenDevice(); 然后获得robot对象:  Robot robot= new Robot(screen); 要获得截屏的方法是:  BufferedImage image= robot.createScreenCapture(new Rectangle(0,0,400,300)); 其中的矩形中的x,y是指绝对的坐标 程序源代码如下: //RobotTest.java  import java.awt.EventQueue; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.image.*; public class RobotTest {     /**      * @param args      */     public static void main(String[] args) {         // TODO Auto-generated method stub         EventQueue.invokeLater(new Runnable(){             public void run()             {                 // make frame with a buuton pannel                                  //ButtonFrame frame = new ButtonFrame();                                  GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();                 GraphicsDevice screen = environment.getDefaultScreenDevice();                 System.out.println(screen.toString());                 try                 {                     Robot robot= new Robot(screen);                     runTest(robot);                 }catch (AWTException e)                 {                           e.printStackTrace();                 }                 //System.exit(0);                   }         });     }         public static void runTest(Robot robot)         {             //simulate a space bar press             robot.keyPress(' ');             robot.keyRelease(' ');                          //simulate a tab key followed by a space             robot.delay(2000);             robot.keyPress(KeyEvent.VK_TAB);             robot.keyRelease(KeyEvent.VK_TAB);                          robot.keyPress(' ');             robot.keyRelease(' ');                          //simulate a mouse click over the rightmost button             robot.delay(2000);             robot.mouseMove(200, 50);             robot.mousePress(InputEvent.BUTTON1_MASK);             robot.mouseRelease(InputEvent.BUTTON1_MASK);                          //capture the screen and show the resulting image             robot.delay(2000);             BufferedImage image= robot.createScreenCapture(new Rectangle(0,0,400,300));             ImageFrame imageF= new ImageFrame(image);             imageF.setVisible(true);             return ;      } } class ImageFrame extends JFrame {     public ImageFrame(Image image)     {         setTitle("Capture");         setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);         JLabel label = new JLabel(new ImageIcon(image));         add(label);     }          public static final int DEFAULT_WIDTH=450;     public static final int DEFAULT_HEIGHT=350; } 运行结果如下:
    转载请注明原文地址: https://ju.6miu.com/read-1312569.html
    最新回复(0)