Combination out of "KeyPress" and "screenshot" doesn't work

Hello everybody :)

After you have answered me the two questions with KeyPress and taking screenshots i've modified and combined them. I thought this would be easy and without any problems ... curiously there is one great mistake :(

When I block the Roboter() the screenshot() function works perfectly. And when I block the screenshot() function the Roboter() one works great. But when i run both together the Roboter() works perfectly, but the screenshot() function doesn't work:O

I have no idea where the problem is. It would be great if you could help me solve it :)

and Here is the code:

  import java.awt.Robot;
  import java.awt.event.KeyEvent;
  import java.awt.AWTException;o
  import java.awt.Rectangle;


  int keyInput[] = {
      KeyEvent.VK_H, KeyEvent.VK_E,
      KeyEvent.VK_L, KeyEvent.VK_L,
      KeyEvent.VK_O, KeyEvent.VK_SPACE, KeyEvent.VK_A,
      KeyEvent.VK_N, KeyEvent.VK_D, KeyEvent.VK_SPACE,
      KeyEvent.VK_T, KeyEvent.VK_H,
      KeyEvent.VK_A, KeyEvent.VK_N,
      KeyEvent.VK_K, KeyEvent.VK_S,
    };

  PImage screenshot; 

  void setup() {
    open("http://google.com"); 
    size(int(displayWidth/2),int(displayHeight));
    noStroke();
    frame.removeNotify();
    frame.setUndecorated(true); 
  }
  void draw() {
    screenshot();
    image(screenshot,0,0,width,height);
    Roboter();
  } 

  void screenshot() {

    try{
      Robot robot_Screenshot = new Robot();
      screenshot = new PImage(robot_Screenshot.createScreenCapture
      (new Rectangle(0,0,displayWidth/2,displayHeight)));
    }
    catch (AWTException e){ }

    frame.setLocation(displayWidth/2, 0);
  }

  void Roboter(){

    try {
        Robot robot = new Robot();
        for (int i = 0; i < keyInput.length; i++) {
          robot.delay(1500);
          robot.keyPress(keyInput[i]);
          robot.delay(100);
          robot.keyRelease(keyInput[i]);
          robot.delay(100);         
        }
    }
    catch (AWTException e){}
  }

Answers

  • What do you mean when you say they don't work? What do they do instead?

    Keep in mind that the robot.delay() function blocks the current thread. In other words, your code won't be able to do anything for the 2 seconds or so every time Roboter (which should be lower-case because it's a method) is called, which is every frame. I would expect that to lead to strange behavior.

  • Thanks for the answer.

    is there an alternative to robot.delay()? and if not, how would you change my code (delete / add a robot.delay()) that only the robot part from void Roboter is blocked?

  • Answer ✓

    We can call a function as a separate thread("")!
    Like this -> thread("Roboter");

Sign In or Register to comment.