如何获取鼠标单击相对于摆动窗口的位置

如何获取鼠标单击相对于摆动窗口的位置

问题描述:

假设我在 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) {
    }
});

参考: