Java Swing GUI

Detect Left, Middle, and Right Mouse Click – Java

In this tutorial, we are going to see how to use MouseAdapter to detect left, middle and right mouse click in Java. This is very useful when you want to add extra functionality to your application. You can make your application behave differently depending on which mouse button the user pressed. Also we’ll see how to get the x and y positions of the mouse on click.


Detect Left, Middle, and Right Mouse Click in Java
import java.awt.event.*; 
import javax.swing.*;
class CheckMouse extends MouseAdapter 
  public void mouseClicked(MouseEvent e) 
    if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
     System.out.println("Left click detected : " + (e.getPoint()));
    if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
     System.out.println("Right click detected : " + (e.getPoint()));
    if ((e.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
     System.out.println("Middle click detected : " + (e.getPoint()));
public class Main 
  public static void main(String[] argv) throws Exception 
      JTextArea text = new JTextArea();
      text.addMouseListener(new CheckMouse());
      JFrame f = new JFrame();
      f.setSize(300, 300);



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 *