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

2022-09-02 11:54:05

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

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

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


答案 1

MouseListener 方法中,您可以执行以下操作:

@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

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

参考:


答案 2

您可以向 GUI 组件添加其左上角像素应作为 [0,0] 点受到威胁,并从 MouseEvent 获取 x 和 yMouseListener

JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {// provides empty implementation of all
                                           // MouseListener`s methods, allowing us to
                                           // override only those which interests us
    @Override //I override only one method for presentation
    public void mousePressed(MouseEvent e) {
        System.out.println(e.getX() + "," + e.getY());
    }
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);