简介

模拟机器人操作测试GUI

code

/*
 * @Author: your name
 * @Date: 2020-11-08 18:22:54
 * @LastEditTime: 2020-11-08 18:38:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /java/calcu/RobotTest.java
 */
package calcu;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

public class RobotTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            ButtonFrame frame = new ButtonFrame();
            frame.setTitle("ButtonTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });

        GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice screen = environment.getDefaultScreenDevice();

        try {
            final Robot robot = new Robot(screen);
            robot.waitForIdle();
            new Thread() {
                public void run() {
                    runTest(robot);
                }
            }.start();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    public static void runTest(Robot robot) {
        robot.keyPress(' ');
        robot.keyRelease(' ');

        // simulate a tab key followed by a space
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_TAB);
        robot.keyRelease(KeyEvent.VK_TAB);
        robot.keyPress(' ');
        robot.keyRelease(' ');
        System.out.println("yellow over");
        // simulate a mouse click over the rightmost button
        robot.delay(1000);
        robot.mouseMove(220, 40);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        System.out.println("mid over");
        robot.delay(1000);
        BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, 400, 300));
        ImageFrame frame = new ImageFrame(image);
        frame.setVisible(true);
    }
}

class ImageFrame extends JFrame {
    private static final int DEFAULT_WIDTH = 450;
    private static final int DEFAULT_HEIGHT = 350;

    public ImageFrame(Image image) {
        setTitle("Capture");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        JLabel label = new JLabel(new ImageIcon(image));
        add(label);
    }
}

posted on 2020-11-08 18:47  HDU李少帅  阅读(154)  评论(0编辑  收藏  举报