Replicating Mouse behavior in Code

2019-09-20 03:35发布

This is related to question: Focus problems with JDK7 and native components.

While working on workarounds we noticed that if we clicked on another component on the window (i.e. a label showing a picture) and then click on the text fields (within the Flash application), everything seemed to work fine. So I've been trying to reproduce that from code but haven't been successful.

Basically, when the mouse is detected hovering over the text box I get notified from the Flash program and I request focus on the label, so when the user clicks on the actual field the label already has the focus.

I request focus like this:

draggableComponent.requestFocus();

Where draggableComponent is the label I've been talking about. I guess this is not equivalent to clicking on the label. What I'm missing?

1条回答
Explosion°爆炸
2楼-- · 2019-09-20 04:17

Finally I found the answer here.

The following example shows how to simulate mouse and key presses in Java using java.awt.Robot class.

try {
    Robot robot = new Robot();

    // Simulate a mouse click
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);

    // Simulate a key press
    robot.keyPress(KeyEvent.VK_A);
    robot.keyRelease(KeyEvent.VK_A);
} catch (AWTException e) {
    e.printStackTrace();
}

The Robot class gave me everything I needed.

查看更多
登录 后发表回答