Java Swing GUI

How to Get Mouse Position on Click Relative to JFrame

In this tutorial, we are going to see how to get mouse position on click relative to JFrame in Java Swing. The coordinates of the mouse each time a click occurs can be found by detecting the click event with an event listener and finding the x and y position of the event.

A MouseEvent object is transmitted to each MouseListener or MouseAdapter object that has registered to receive mouse events using the component’s addMouseListener method. (MouseAdapter objects implement MouseListener interface.) Each of these listener objects gets a MouseEvent containing the mouse event.
 


 

Java Program to Get Mouse Position on Click Relative to JFrame:
import java.awt.event.*; 
import javax.swing.*;
 
public class Main {
  public static void main(String[] argv)
  {  
  JFrame f = new JFrame();
  JPanel panel = new JPanel();
  f.add(panel);
  panel.addMouseListener(new MouseAdapter() {
    @Override 
    public void mousePressed(MouseEvent e) {
      System.out.println(e.getX() + "," + e.getY());
    }
  });
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  f.setSize(200, 200);
  f.setVisible(true);
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *