How to get location of a mouse click relative to a swing window

后端 未结 4 1632
生来不讨喜
生来不讨喜 2020-11-27 20:54

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 mouse         


        
4条回答
  •  青春惊慌失措
    2020-11-27 21:52

    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
    }
    

    Simply add this to your Component by:

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

    Reference:

    • How to Write a Mouse Listener

提交回复
热议问题