查找相对于面板的鼠标位置 [英] Finding Mouse Position relative to a panel

查看:101
本文介绍了查找相对于面板的鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取鼠标在面板中的位置,如面板左上角= x/y 0,0.

I'm trying to get the mouse's position within a panel, as in the top left of the panel = x/y 0,0.

我一分钟拥有的东西会在整个屏幕上显示位置,因此取决于面板(在框架中)在屏幕上的位置,坐标是不同的.我猜您可以添加x/y坐标来解决这个问题,但这似乎是一个混乱的解决方案.有人可以帮忙吗?

What I have at the minute gives the position on the entire screen, so depending on where the panel (which is in a frame) is on the screen, the coordinates are different. I guess you could add to the x/y co-ordinates to account for this, but this seems like a messy solution. Can anyone help?

这是我正在使用的mouseListener,已添加到面板中.

Here's the mouseListener I'm using, which has been added to the panel.

private class MouseListener extends MouseAdapter 
{
    public void mouseClicked(MouseEvent e) 
    {
        // Finds the location of the mouse
        PointerInfo a = MouseInfo.getPointerInfo();
        Point b = a.getLocation();

        // Gets the x -> and y co-ordinates
        int x = (int) b.getX();
        int y = (int) b.getY();
        System.out.println("Mouse x: " + x);
        System.out.println("Mouse y: " + y);

        // Determines which tile the click occured on
        int xTile = x/tileSize;
        int yTile = y/tileSize;

        System.out.println("X Tile: " + xTile);
        System.out.println("Y Tile: " + yTile);

    }
}

推荐答案

请参见

返回事件相对于源组件的x,y位置.

这篇关于查找相对于面板的鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆