简体   繁体   中英

Infinite call of Keyevent on Ubuntu

I need to create key event on host computer. So, I made a simple java code like this.

import java.awt.event.KeyEvent;
import java.awt.Robot;
import java.io.IOException;
public class Hello {
    public static void main(String[] args) throws IOException {
    try {
        try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_F11);
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

When I execute this code on windows using Eclipse , keyevent for F11 is triggered just one time 5 seconds later. However, when I execute this on Ubuntu(12.04) using Eclipse or commands ( javac and java ), the keyevent seems to be triggered continuously. (it seems to go into infinite loop) Java version was 1.6 and 1.7 on Ubuntu .

I don;t know why this happens. Anybody knows a solution for this?

You need to release the key as well (to simulate a key type)...

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_F11);
Thread.sleep(250);    
robot.keyRelease(KeyEvent.VK_F11);

Other wise the system will think you're holding the key down...

ps- I find adding a small delay helps improve the overall functionality. You can set a automatic delay directly within the Robot. See Robot#setAutoDelay for more details

As said in the JavaDoc , you have to "release" the key after pressing it :

robot.keyPress(KeyEvent.VK_F11);
robot.keyRelease(KeyEvent.VK_F11);

It remains "pressed" until you release it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM