Pablo Lira
Pablo Lira

Reputation: 11

Get mouse position constantly in java relative to Jframe

I'm creating a java app and I need to get every frame the position of the mouse relative to my Jframe. I'm writing a class that extends from MouseAdapter but I cannot access to MouseEvent when I need it.

Thanks.

Upvotes: 1

Views: 1819

Answers (1)

Acrosicious
Acrosicious

Reputation: 46

Using a Swing Timer: Prints the relative distance to the upper left edge of the JFrame.

public static void main(String[] args) {
    JFrame frame = new JFrame("Frame");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

    Timer timer = new Timer(66, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Point p = MouseInfo.getPointerInfo().getLocation();
            p = new Point(p.x - frame.getLocation().x, p.y - frame.getLocation().y);
            System.out.println("Mouse: " + p);

        }
    });
    timer.start();

}

Upvotes: 2

Related Questions