preload
Dez 17

I just stumbled upon an article about the java.awt.robot from java while reading java stuff. When you would like to fill textboxes or to click buttons etc. on an swing or awt window automatically you can use the java.awt.robot class.

Check this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 
package desktopapplication1;
 
import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.Point;
import java.awt.event.InputEvent;
import org.jdesktop.application.FrameView;
 
public class Robot implements Runnable {
 
    private FrameView frameview;
 
    public Robot(FrameView frameview) {
        this.frameview = frameview;
    }
 
    public void run() {
        try {
            initRobot();
        } catch (AWTException ex) {
            Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
        private void initRobot() throws AWTException {
        // create a robot to feed in GUI events
 
        java.awt.Robot rob = new java.awt.Robot();
 
        // enter some keystrokes
 
        int keyinput[] = {
            KeyEvent.VK_T,
            KeyEvent.VK_E,
            KeyEvent.VK_S,
            KeyEvent.VK_T,
            KeyEvent.VK_I,
            KeyEvent.VK_N,
            KeyEvent.VK_G
        };
        rob.delay(1000);
        rob.keyPress(KeyEvent.VK_SHIFT);
 
        ((DesktopApplication1View)this.frameview).getjTextField1().requestFocus();
        for (int i = 0; i < keyinput.length; i++) {
            rob.keyPress(keyinput[i]);
            rob.delay(1000);
        }
        rob.keyRelease(KeyEvent.VK_SHIFT);
        rob.keyPress(KeyEvent.VK_ENTER);
 
        // move cursor to exit button
 
        Point p = ((DesktopApplication1View)this.frameview).getjButton1().getLocationOnScreen();
        rob.mouseMove(p.x + 5, p.y + 5);
        rob.delay(2000);
 
        // press and release left mouse button
 
        rob.mousePress(InputEvent.BUTTON1_MASK);
        rob.delay(2000);
        rob.mouseRelease(InputEvent.BUTTON1_MASK);
 
    }
 
}

I started the class in a separate thread, the example from sun, where I took most parts of the code uses ActionListener to update the textfield.

Now you have to start the thread with:

1
2
       Thread t = new Thread(new desktopapplication1.Robot(this));
       t.start();

Check the example from sun – http://java.sun.com/developer/TechTips/2000/tt0711.html

Leave a Reply

You must be logged in to post a comment.