简体   繁体   English

设置光标在jframe中的位置

[英]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. 它设置光标在屏幕上的位置,而不是jframe。 Also, when i say if(mousex >= 700) it also gets it from the screen. 另外,当我说if(mousex> = 700)时,它也会从屏幕上获取。 I need to know how to change it to be of the jframe instead. 我需要知道如何将其更改为jframe。 Thanks. 谢谢。

Get the location of the JFrame on the Screen and simply translate your mouse position accordingly. 获取JFrame在屏幕上的位置 ,然后简单地相应地转换鼠标位置。 All objects that extend Components, including JFrame, have the method getLocationOnScreen() . 所有扩展Components的对象(包括JFrame)都具有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. 因此,再次使用此方法,获取JFrame的位置,然后查找鼠标的相对位置,包括鼠标的位置和所需位置。

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. 您可能希望只创建一次Robot对象,并在需要时使用该对象,而不是每次都重新创建它。

Things you can get, 你可以得到的东西

  1. JFrame's on screen location. JFrame在屏幕上的位置。
  2. Once you know the on screen location you can just add those (x,y) and get the new location inside your JFrame. 一旦知道了屏幕上的位置,就可以添加(x,y)并在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) 如果计算后的位置超过的尺寸JFrame然后设置x或y到的最大电流大小JFrame (如果共祝是完全动态的)

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 . 在上图中, JFrame在屏幕上的位置是(50,50),这意味着JFrame内部组件的坐标变为(0,0)。 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. 现在,在JFrame内获取鼠标在屏幕上的位置,您只需说出JFrame内的一些所需的随机坐标,然后将这些屏幕位置50添加到其中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM