Set cursor location in 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 this works fine, except for one. It sets the position of the cursor on the screen, not the jframe. Also, when I say (mousex> = 700), it also gets it from the screen. I need to know how to change it to jframe. Thanks.

+4
source share
2 answers

Get the location of the JFrame on the screen and just move the mouse position accordingly. All objects that extend components, including the JFrame, have the getLocationOnScreen() method. So use this method again, find the location of the JFrame, and then find the relative locations of the mouse, both where and where you want.

This can be solved using class algebra.

Edit
You might want to create your Robot object only once and just use the object as needed, rather than re-create it every time.

+3
source

What can you get

  • JFrame on the screen.
  • Once you know the location on the screen, you can just add these (x, y) and get a new place in your JFrame.
  • If the location after calculation is larger than the JFrame size, then set x or y to MAX size of the current JFrame size (If the coordinates are fully dynamic)

Visually something like this

enter image description here

In the above image, the location on the JFrame screen is (50.50), which means that the coordinate becomes (0,0) for the components inside the JFrame . Now find the location of the mouse on the screen inside the JFrame , you can just say some random desired coordinate inside the JFrame, and then add 50 screen layout to it.

+3
source

All Articles