Home » Desktop Java » awt » event » Detect double or triple click example

About Ilias Tsagklis

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

Detect double or triple click example

With this tutorial we are going to see how can you detect double or triple clicks in a Java Desktop application. This is very useful when you want the user to have rich interaction with your application using his mouse. You can also add extra functionality according to how many clicks the user did with the mouse.

In short all you have to do in order to detect double or triple clicks is:

  • Create a class that extends MouseAdapter
  • Override mouseClicked method in order to further customize the handling of that specific event. Now every time the user clicks a mouse button this method will be executed.

Let’s take a look a the code:

package com.javacodegeeks.snippets.desktop;

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

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

public class Main {

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

  JFrame jFrame = new JFrame();

  JTextField textField = new JTextField();

  textField.addMouseListener(new ClickListener());

  jFrame.add(textField);

  jFrame.setSize(800, 600);

  jFrame.setVisible(true);

  textField.addMouseListener(new ClickListener());
    }
}

class ClickListener extends MouseAdapter {

    @Override
    public void mouseClicked(MouseEvent event) {

  if (event.getClickCount() == 2) {

System.out.println("Double click detected");

  } else if (event.getClickCount() == 3) {

System.out.println("Triple click detected");

  }

    }
}

 
This was an example on how to detect detect double or triple click.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

 

Leave a Reply

avatar
  Subscribe  
Notify of