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

一曲冷凌霜 提交于 2019-12-10 19:01:57

问题


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.

Does anyone know of an alternative way to simulate a mousePressed event?

This is the code I used:

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

回答1:


If you want to simulate the click action on a JButton you can invoke the doClick method, take a look here. Otherwise, maybe this similar question can help you. Hope this helps.




回答2:


I had the same issue with using java.awt.robot.mousePress(int button) not working on a mac os x 10.8 by checking

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);  



回答3:


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

MouseAdapter mouseAction = new ContractMouseAdapter(Component);


来源:https://stackoverflow.com/questions/5528791/how-can-i-simulate-a-mousepressed-event-without-using-java-awt-robot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!