如何获取鼠标单击相对于摆动窗口的位置 [英] How to get location of a mouse click relative to a swing window

查看:32
本文介绍了如何获取鼠标单击相对于摆动窗口的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Java Swing JFrame 中.我点击我的鼠标.我想在 GUI 中获取鼠标单击的位置.在java中,该行

Say I'm in a Java Swing JFrame. I click my mouse. I want to get the location of the mouse click within the GUI. In java, the line

int mouseX = MouseInfo.getPointerInfo().getLocation.x;

似乎给出了鼠标在整个屏幕上的位置.我如何获得它相对于 GUI 的位置?

Seems to give the location of the mouse on the entire screen. How would I get it's location relative to the GUI?

推荐答案

来自 MouseListener 方法:

From MouseListener methods you can do:

@Override
public void mouseClicked(MouseEvent e) {
    int x=e.getX();
    int y=e.getY();
    System.out.println(x+","+y);//these co-ords are relative to the component
}

只需通过以下方式将其添加到您的 Component:

Simply add this to your Component by:

component.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
    }
});

参考:

这篇关于如何获取鼠标单击相对于摆动窗口的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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