Handling Mouse Clicks

In this short tutorial we are going to see how to monitor a very basic GUI event in Java Desktop Applications, which is mouse clicks. What we want to see is what button mouse the user pressed (left, middle or right click) and then we want to know the exact location, in coordinates, in our Frame that this event occurred.

In short, to handle mouse clicks in a Java AWT application :

  • Create a JFrame
  • Create a MouseListener and add it to the JFrame
  • Use MouseEvent.getModifiers() and InputEvent masks to see what button of the mouse the user clicked
  • Use MouseEvent.getPoint() to get the coordinates of the point that the users clicked into.
So, let’s see the code snippet bellow:
package com.javacodegeeks.snippets.desktop;

import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class HandlingMouseClicks {

    public static void main(String[] argv) throws Exception {

  // Create a new JFrame window

  JTextField compnt = new JTextField();

  compnt.addMouseListener(new MouseListener());

  JFrame frame = new JFrame();


  frame.setSize(800, 800);



class MouseListener extends MouseAdapter {

    public void mouseClicked(MouseEvent event) {

  if ((event.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {

System.out.println("left" + (event.getPoint()));


  if ((event.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {

System.out.println("middle" + (event.getPoint()));


  if ((event.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {

System.out.println("right" + (event.getPoint()));



 leftjava.awt.Point[x=556,y=253] leftjava.awt.Point[x=512,y=394] leftjava.awt.Point[x=512,y=394] 

This was an example on how to handle mouse clicks in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button