sandspro
sandspro

Reputation: 72

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.

Upvotes: 4

Views: 5433

Answers (2)

TeaCupApp
TeaCupApp

Reputation: 11452

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,

enter image description here

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.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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.

Upvotes: 3

Related Questions