java 如何让机器人按住鼠标按钮一段时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6401467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:45:38  来源:igfitidea点击:

How can I make Robot press and hold a mouse button for a certain period of time?

javaswingmouseeventawtrobot

提问by Neutralise

I am using Java to generate a mouse press using the Robot class:

我正在使用 Java 使用 Robot 类生成鼠标按下:

robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);

However, I want the Robot to press the button for a certain period of time. How can I achieve this?

但是,我希望机器人按下按钮一段时间。我怎样才能做到这一点?

回答by Martijn Courteaux

Just sleep a bit between the two actions (specified in milliseconds):

只需在两个操作之间稍作睡眠(以毫秒为单位):

  1. Thread.sleep(long millis);

    robot.mousePress(InputEvent.BUTTON1_MASK);
    try { Thread.sleep(1000); } catch(Exception e) {} // Click one second
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    
  2. Robot.delay(long millis);

    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(1000); // Click one second
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    
  1. Thread.sleep(long millis);

    robot.mousePress(InputEvent.BUTTON1_MASK);
    try { Thread.sleep(1000); } catch(Exception e) {} // Click one second
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    
  2. Robot.delay(long millis);

    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(1000); // Click one second
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    

回答by SteeveDroz

I did that, it's simple: when you detect the mouse is pressed, you save the System.currentTimeMillis(). When you detect the mouse is released, you just check how long it was pressed.

我这样做了,很简单:当你检测到鼠标被按下时,你保存System.currentTimeMillis().当您检测到鼠标被释放时,您只需检查它被按下的时间。

If you want the action to be made after a certain amount of time, even if the mouse is still pressed, you start a thread that lives the desired amount of time when pressed and you interrupt it when releasing. If the thread isn't interrupted in the amount of time you wanted, the action will be performed.

如果您希望在一定时间后执行操作,即使鼠标仍被按下,您也可以启动一个线程,该线程在按下时存活所需的时间,并在释放时中断它。如果线程在您想要的时间内没有被中断,则将执行该操作。