下面列出了怎么用java.awt.Robot的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(50);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
toolkit.realSync();
Point point = getRowPointToClick(2);
robot.mouseMove(point.x, point.y);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
}
public static void main(String[] args) throws Throwable {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
constructTestUI();
}
});
Util.waitForIdle(null);
try {
Point loc = textArea.getLocationOnScreen();
Util.drag(new Robot(),
new Point((int) loc.x + 3, (int) loc.y + 3),
new Point((int) loc.x + 40, (int) loc.y + 40),
InputEvent.BUTTON1_MASK);
} catch (AWTException ex) {
throw new RuntimeException("Could not initiate a drag operation");
}
Util.waitForIdle(null);
}
public static void main(String[] args) throws Exception {
if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
return;
}
Robot robot = new Robot();
robot.setAutoDelay(50);
createAndShowGUI();
// Pressed keys: Alt + E + A
// Results: ALT + VK_DEAD_ACUTE + a with accute accent
keyPress(robot, KeyEvent.VK_ALT);
keyPress(robot, KeyEvent.VK_E);
keyRelease(robot, KeyEvent.VK_E);
keyRelease(robot, KeyEvent.VK_ALT);
keyPress(robot, KeyEvent.VK_A);
keyRelease(robot, KeyEvent.VK_A);
if (state != 3) {
throw new RuntimeException("Wrong number of key events.");
}
}
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
final ScrollPaneValidateTest obj = new ScrollPaneValidateTest();
obj.setVisible(true);
// set to some scroll position
obj.pane.setScrollPosition(600, 200);
// get the newly set position
Point scrollPosition = obj.pane.getScrollPosition();
// call validate multiple times
obj.pane.validate();
robot.delay(1000);
obj.pane.validate();
robot.delay(1000);
// compare position after calling the validate function
if(!scrollPosition.equals(obj.pane.getScrollPosition())) {
obj.dispose();
throw new RuntimeException("Scrolling position is changed in ScrollPane");
}
obj.dispose();
return;
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createAndShowUI();
}
});
toolkit.realSync();
clickCell(robot, 1, 1);
Util.hitKeys(robot, KeyEvent.VK_BACK_SPACE, KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE);
toolkit.realSync();
clickColumnHeader(robot, 1);
toolkit.realSync();
clickColumnHeader(robot, 1);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(() -> {
new RemovedComponentMouseListener();
});
Robot r = Util.createRobot();
r.setAutoDelay(100);
r.waitForIdle();
Util.pointOnComp(button, r);
r.waitForIdle();
r.mousePress(InputEvent.BUTTON1_MASK);
r.waitForIdle();
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.waitForIdle();
if (!mouseReleasedReceived) {
throw new RuntimeException("mouseReleased event was not received");
}
}
public static void main(final String[] args) throws AWTException {
final Window window = new BackgroundIsNotUpdated(null);
window.setSize(300, 300);
window.setLocationRelativeTo(null);
window.setVisible(true);
sleep();
window.setBackground(Color.GREEN);
sleep();
final Robot robot = new Robot();
robot.setAutoDelay(200);
Point point = window.getLocationOnScreen();
Color color = robot.getPixelColor(point.x + window.getWidth() / 2,
point.y + window.getHeight() / 2);
window.dispose();
if (!color.equals(Color.GREEN)) {
throw new RuntimeException(
"Expected: " + Color.GREEN + " , Actual: " + color);
}
}
public static void main(final String[] args) throws AWTException {
final bug7097771 frame = new bug7097771();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
final Button button = new Button();
button.addActionListener(frame);
frame.add(button);
frame.setVisible(true);
sleep();
frame.setEnabled(false);
button.setEnabled(false);
button.setEnabled(true);
sleep();
Util.clickOnComp(button, new Robot());
sleep();
frame.dispose();
if (action) {
throw new RuntimeException("Button is not disabled.");
}
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Frame frame = new Frame();
frame.setSize(300, 200);
TextField textField = new TextField();
frame.add(textField);
frame.setVisible(true);
toolkit.realSync();
textField.requestFocus();
toolkit.realSync();
// Check that the system assertion dialog does not block Java
Robot robot = new Robot();
robot.setAutoDelay(50);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
toolkit.realSync();
frame.setVisible(false);
frame.dispose();
}
public static void main(String[] args) throws Exception {
robot = new Robot();
String name = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(name);
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException e) {
throw new RuntimeException("Test Failed");
}
createUI();
robot.waitForIdle();
executeTest();
if (!"".equals(errorMessage)) {
throw new RuntimeException(errorMessage);
}
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Frame frame = new Frame();
frame.setSize(300, 300);
frame.setVisible(true);
toolkit.realSync();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DELETE);
robot.keyRelease(KeyEvent.VK_DELETE);
toolkit.realSync();
frame.dispose();
if (eventsCount != 3) {
throw new RuntimeException("Wrong number of key events: " + eventsCount);
}
}
public void moveTo(
Robot r,
Point b,
Point e)
{
Point2D.Double ee = new Point2D.Double(e.getX(), e.getY());
Point2D.Double bb = new Point2D.Double(b.getX(), b.getY());
final int count = (int)(ee.distance(bb));
Point2D.Double c = new Point2D.Double(bb.getX(), bb.getY());
for(int i=0; i<count; ++i){
c.setLocation(
bb.getX() + (ee.getX()-bb.getX())*i/count,
bb.getY() + (ee.getY()-bb.getY())*i/count);
r.mouseMove(
(int)c.getX(),
(int)c.getY());
r.delay(5);
}
r.mouseMove(
(int)ee.getX(),
(int)ee.getY());
r.delay(5);
}
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
final ScrollPaneValidateTest obj = new ScrollPaneValidateTest();
obj.setVisible(true);
// set to some scroll position
obj.pane.setScrollPosition(600, 200);
// get the newly set position
Point scrollPosition = obj.pane.getScrollPosition();
// call validate multiple times
obj.pane.validate();
robot.delay(1000);
obj.pane.validate();
robot.delay(1000);
// compare position after calling the validate function
if(!scrollPosition.equals(obj.pane.getScrollPosition())) {
obj.dispose();
throw new RuntimeException("Scrolling position is changed in ScrollPane");
}
obj.dispose();
return;
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(50);
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
}
});
toolkit.realSync();
if (OSInfo.OSType.MACOSX.equals(OSInfo.getOSType())) {
Util.hitKeys(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_L);
} else {
Util.hitKeys(robot, KeyEvent.VK_ALT, KeyEvent.VK_L);
}
checkFocus();
}
private void init(Region region) {
try {
robot = new Robot();
} catch (AWTException e1) {
e1.printStackTrace();
}
content = getJPanel();
_region = region;
Rectangle rect = _region.getRect();
content.setPreferredSize(rect.getSize());
add(content);
setBounds(rect);
getRootPane().putClientProperty("Window.shadow", Boolean.FALSE);
((JPanel) getContentPane()).setDoubleBuffered(true);
setVisible(false);
setFocusableWindowState(false);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(() -> {
new RemovedComponentMouseListener();
});
Robot r = Util.createRobot();
r.setAutoDelay(100);
r.waitForIdle();
Util.pointOnComp(button, r);
r.waitForIdle();
r.mousePress(InputEvent.BUTTON1_MASK);
r.waitForIdle();
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.waitForIdle();
if (!mouseReleasedReceived) {
throw new RuntimeException("mouseReleased event was not received");
}
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(() -> {
new RemovedComponentMouseListener();
});
Robot r = Util.createRobot();
r.setAutoDelay(100);
r.waitForIdle();
Util.pointOnComp(button, r);
r.waitForIdle();
r.mousePress(InputEvent.BUTTON1_MASK);
r.waitForIdle();
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.waitForIdle();
if (!mouseReleasedReceived) {
throw new RuntimeException("mouseReleased event was not received");
}
}
public ImageTransmitter(DatagramSocket socket, InetAddress remoteHost, int remotePort, Rectangle area) {
try {
robot = new Robot();
maxI = (int) Math.ceil(area.getWidth() / tileWidth);
maxJ = (int) Math.ceil(area.getHeight() / tileWidth);
tiles = new int[maxI][maxJ][tileWidth * tileWidth];
this.area = area;
this.socket = socket;
localHost = socket.getLocalAddress();
localPort = socket.getLocalPort();
this.remoteHost = remoteHost;
this.remotePort = remotePort;
this.encoder = new DefaultEncoder();
transmit = true;
}
catch (AWTException e) {
LOGGER.log(Level.WARNING, "exception", e);
}
}
public static void mouseDND(Robot robot, int x1, int y1, int x2, int y2) {
int N = 20;
int x = x1;
int y = y1;
int dx = (x2 - x1) / N;
int dy = (y2 - y1) / N;
robot.mousePress(InputEvent.BUTTON1_MASK);
for (int i = 0; i < N; i++) {
robot.mouseMove(x += dx, y += dy);
}
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(50);
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
}
});
toolkit.realSync();
if (OSInfo.OSType.MACOSX.equals(OSInfo.getOSType())) {
Util.hitKeys(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_L);
} else {
Util.hitKeys(robot, KeyEvent.VK_ALT, KeyEvent.VK_L);
}
checkFocus();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(DemandGTK::createAndShow);
Robot robot = new Robot();
robot.waitForIdle();
robot.delay(1000);
SwingUtilities.invokeAndWait( () -> {
frame.setVisible(false);
frame.dispose();
});
}
public static void main(String[] args) {
Robot robot = Util.createRobot();
Frame frame = new Frame("Frame");
frame.setBackground(Color.BLUE);
frame.setBounds(200, 50, 300, 300);
frame.setVisible(true);
Dialog dialog1 = new Dialog(frame, "Dialog 1", false);
dialog1.setBackground(Color.RED);
dialog1.setBounds(100, 100, 200, 200);
dialog1.setVisible(true);
Dialog dialog2 = new Dialog(frame, "Dialog 2", false);
dialog2.setBackground(Color.GREEN);
dialog2.setBounds(400, 100, 200, 200);
dialog2.setVisible(true);
Util.waitForIdle(robot);
Util.clickOnComp(dialog2, robot);
Util.waitForIdle(robot);
Point point = dialog1.getLocationOnScreen();
int x = point.x + (int)(dialog1.getWidth() * 0.9);
int y = point.y + (int)(dialog1.getHeight() * 0.9);
try {
if (!Util.testPixelColor(x, y, dialog1.getBackground(), 10, 100, robot)) {
throw new RuntimeException("Test FAILED: Dialog is behind the frame");
}
} finally {
frame.dispose();
dialog1.dispose();
dialog2.dispose();
}
}
public static void main(String[] args) throws Exception {
robot = new Robot();
robot.setAutoDelay(100);
robot.waitForIdle();
UIManager.LookAndFeelInfo[] lookAndFeelArray
= UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo lookAndFeelItem : lookAndFeelArray) {
executeCase(lookAndFeelItem.getClassName());
}
}
public void snapshot() {
try {
Robot robot = new Robot();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
image = robot.createScreenCapture(
new Rectangle(0, 0, d.width, d.height));
} catch (AWTException e) {
e.printStackTrace();
}
}
private static void checkFileChooser() throws Exception {
if (System.getSecurityManager() == null) {
throw new RuntimeException("Security manager is not set!");
}
Robot robot = new Robot();
robot.setAutoDelay(50);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
fileChooserIsShown = true;
System.out.println("Start file chooser: " + fileChooserIsShown);
}
});
long time = System.currentTimeMillis();
while (fileChooser == null) {
if (System.currentTimeMillis() - time >= 10000) {
throw new RuntimeException("FileChoser is not shown!");
}
Thread.sleep(500);
}
Thread.sleep(500);
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
System.exit(0);
}
private static void showFrame() throws Exception {
final Robot robot = new Robot();
robot.setAutoDelay(50);
createUI();
images[step] = robot.createScreenCapture(bounds);
SwingUtilities.invokeAndWait(frame::dispose);
sleep();
}
public static void screenShot() throws IOException, AWTException, EmailException {
Properties pro = getProperties();
String filePath = pro.getProperty("RobotWorkPlace")+"PrtSc/screen.jpg";
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage bim = new Robot().createScreenCapture(new Rectangle(
0, 0, dim.width, dim.height));
ImageIO.write(bim, "jpg", new File(filePath));
//�ʼ����ͽ�ͼ
MailUtil.sendPic("ScreenShot", filePath);
}
public static void main(String[] args) throws Exception {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(50);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createAndShowGUI();
}
});
toolkit.realSync();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
fileChooser.setSelectedFile(file);
}
});
toolkit.realSync();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
toolkit.realSync();
if (!defaultKeyPressed) {
throw new RuntimeException("Default button is not pressed");
}
}
public static void main(String[] args) throws InterruptedException, java.lang.reflect.InvocationTargetException
{
final Frame frame = new Frame("the test");
frame.setLayout(new FlowLayout());
final Button btn1 = new Button("button 1");
frame.add(btn1);
frame.add(new Button("button 2"));
frame.add(new Button("button 3"));
frame.pack();
frame.setVisible(true);
Robot r = Util.createRobot();
Util.waitForIdle(r);
Util.clickOnComp(btn1, r);
Util.waitForIdle(r);
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (kfm.getFocusOwner() != btn1) {
throw new RuntimeException("test error: can not set focus on " + btn1 + ".");
}
EventQueue.invokeAndWait(new Runnable() {
public void run() {
final int n_comps = frame.getComponentCount();
for (int i = 0; i < n_comps; ++i) {
frame.getComponent(i).setVisible(false);
}
}
});
Util.waitForIdle(r);
final Component focus_owner = kfm.getFocusOwner();
if (focus_owner != null && !focus_owner.isVisible()) {
throw new RuntimeException("we have invisible focus owner");
}
System.out.println("test passed");
frame.dispose();
}
private static void setFocus(final Component comp, final Robot r) {
if (comp.hasFocus()) {
return;
}
Util.clickOnComp(comp, r);
Util.waitForIdle(r);
if (!comp.hasFocus()) {
throw new RuntimeException("can not set focus on " + comp);
}
}