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

后端 未结 4 1618
生来不讨喜
生来不讨喜 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:28

    You can add MouseListener to GUI component whose top left pixel should be threated as [0,0] point, and get x and y from MouseEvent

    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);
    

提交回复
热议问题