Java – hold the mouse in ellipse2d

I know how to keep my mouse (my g.draw (mousex, mousey) cursor) in ellipse2d / shape

@Override
public void mouseMoved(MouseEvent e) {
    int x = e.getX(),y = e.getY();
    if(shape.contains(x,y)) {
        mouseMoveX = e.getX();
        mouseMoveY = e.getY();
    }
}

... but when the mouse leaves the shape (until it returns), this will completely lock the motion Ie remains in the same position even if the actual cursor moves I want the mouse to move around the ellipse, even if the actual cursor has come out Many of you may still be confused. I'm sorry. If you need more explanation, I'd be happy to help In addition, the first question here, if I violate any rules, please tell me! thank you.

PS: for any late reply, you are currently on dial-up Internet:(

Solution

The easiest way is to use Java awt. Robot class, which allows you to directly control the mouse and keyboard:

import java.awt.Robot;

...

Robot robot = new Robot(<your GraphicsDevice>);

...

@Override
public void mouseMoved(MouseEvent e) {
    int x = e.getX(),y)) {
        mouseMoveX = e.getX();
        mouseMoveY = e.getY();
    }
    else {
        robot.mouseMove(mouseMoveX,mouseMoveY); // Assuming these are the prevIoUs coordinates.
    }
}

Editor: OK, try this:

@Override
public void mouseMoved(MouseEvent e) {
    int x = e.getX(),y = e.getY();
    if (shape.contains(x,y)) {
        mouseMoveX = e.getX();
        mouseMoveY = e.getY();
    }
    else {
        // get angle of rotation
        double r = Math.atan2(y-shape.getCenterY(),x-shape.getCenterX());
        mouseMoveX = (int) (shape.getWidth()/2 * Math.cos(r) + shape.getCenterX());
        mouseMoveY = (int) (shape.getHeight()/2 * Math.sin(r) + shape.getCenterY());
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>