简体   繁体   中英

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.

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

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.

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

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

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