Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

The AWT Robot!

This topic may not be of immediate use to everyone, but sometimes an API is just interesting enough that it deserves mentioning. In Java 1.3, a class with the intriguing name java.awt.Robot was added. The AWT robot provides an API for generating input events such as keystrokes and mouse gestures programmatically. It could be used to build automated GUI testing tools and the like. The following example uses the Robot class to move the mouse to the upper-left area of the screen and perform a series of events corresponding to a double-click. On most Windows systems, this opens up the My Computer folder that lives in that region of the screen.

    public class RobotExample
    {
        public static void main( String [] args ) throws Exception
        {
            Robot r = new Robot();
            r.mouseMove(35,35);
            r.mousePress( InputEvent.BUTTON1_MASK );
            r.mouseRelease( InputEvent.BUTTON1_MASK );
            Thread.sleep(50);
            r.mousePress( InputEvent.BUTTON1_MASK );
            r.mouseRelease( InputEvent.BUTTON1_MASK );
        }
    }

In addition to its magic fingers, the AWT robot also has eyes! You can use the Robot class to capture an image of the screen or a rectangular portion of it by using the createScreenCapture() method. (Note that you can get the exact dimensions of the screen from the AWT’s getScreenSize() method.)

Java 5.0 added a correspondingly useful API, java.awt.MouseInfo, which allows the gathering of mouse movement information from anywhere on the screen (not restricted to the area within the Java application’s windows). The combination ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content