简体   繁体   English

如何在不使用java.awt.robot的情况下模拟mousePressed事件?

[英]How can I simulate a mousePressed event without using java.awt.robot?

I want to simulate a mousePressed event in Java, I found out that I can use the Robot class for this, and it works, but only in Windows and not in Mac OS X. 我想在Java中模拟一个mousePressed事件,我发现我可以使用Robot类,它可以工作,但只能在Windows中使用,而不能在Mac OS X中使用。

Does anyone know of an alternative way to simulate a mousePressed event? 有没有人知道模拟mousePressed事件的另一种方法?

This is the code I used: 这是我使用的代码:

Robot robot = new Robot();
robot.mousePress(InputEvent.BUTTON1_MASK);

If you want to simulate the click action on a JButton you can invoke the doClick method, take a look here . 如果要模拟JButton上的单击操作,可以调用doClick方法,请查看此处 Otherwise, maybe this similar question can help you. 否则,也许这个类似的问题可以帮助你。 Hope this helps. 希望这可以帮助。

I had the same issue with using java.awt.robot.mousePress(int button) not working on a mac os x 10.8 by checking 我使用java.awt.robot.mousePress(int按钮)不能在mac os x 10.8上工作时遇到同样的问题

int b = InputEvent.getMaskForButton(MouseEvent.BUTTON1); //1024  
int c = InputEvent.BUTTON1_MASK; //8  
// works on mac  
Robot r = new Robot();  
r.mouseMove(500, 500);  
r.mousePress(1024);  
r.mouseRelease(1024);  

Here is a sample code that will help. 这是一个有用的示例代码。

private final class ContractMouseAdapter extends MouseAdapter {

    @Override
    public void mousePressed(MouseEvent e) {
        // Do whatever you want.
    }

}

And call this adapter in ur Swing code as 并在你的Swing代码中调用此适配器

MouseAdapter mouseAction = new ContractMouseAdapter(Component);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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