简体   繁体   中英

Set location of cursor within jframe

I have a program that uses the following code:

public void mouseMoved(MouseEvent e) {
    mousex = e.getX();
    mousey = e.getY();

    if(mousex >= 700) {
        try {
            Robot robot = new Robot();

            robot.mouseMove(0, 0);
        } catch (AWTException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
    if(mousex <= 100) {
        Robot robot;
        try {
            robot = new Robot();
            robot.mouseMove(0, 0);
        } catch (AWTException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}

All of it works fine except one thing. It sets the position of the cursor on the screen not the jframe. Also, when i say if(mousex >= 700) it also gets it from the screen. I need to know how to change it to be of the jframe instead. Thanks.

Get the location of the JFrame on the Screen and simply translate your mouse position accordingly. All objects that extend Components, including JFrame, have the method getLocationOnScreen() . So again, use this method, get the location of the JFrame and then find the relative locations of the mouse, both where it is, and where you want it.

This can be solved with grade school algebra.

Edit
You may wish to create your Robot object just once and simply use the object when needed rather than re-creating it each time.

Things you can get,

  1. JFrame's on screen location.
  2. Once you know the on screen location you can just add those (x,y) and get the new location inside your JFrame.
  3. If the location after calculation is more than the size of JFrame then set the x or y to the MAX current size of JFrame (If the co-ordinations are completely dynamic)

Visually something like this,

在此处输入图片说明

In above image, The location on screen of JFrame is (50,50) that means those co-ordinate becomes (0,0) for components inside the JFrame . Now the get the mouse location on screen inside JFrame you can just say Some random desired co-ordinate inside a JFrame and than add those screen location 50 into it.

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