Mouse Double Click Example Java

The code explains how to handle double clicks of mouse key. You even can handle triple clicks also, if required.

Example on Mouse Double Click Example
import java.awt.*;
import java.awt.event.*;

public class Demo extends Frame
{
  Button btn;
  public Demo()
  {
    setLayout(new FlowLayout());
    btn = new Button("OK");

    btn.addMouseListener(new MyListener());

    add(btn);
    setSize(300,300);
    setVisible(true);
  }
  public static void main(String args[])
  {
    new Demo();
  }
}
class MyListener  extends MouseAdapter
{
  public void mouseClicked (MouseEvent e) 
  {
    if(e.getClickCount() == 2) 
    {				// write here your event handling code
      System.out.println("You clicked two times on the button");   
    }
  }
}


Mouse Double Click Example
Output screen on Mouse Double Click Example

btn.addMouseListener(new MyListener());

Instead of button btn, it can be any GUI component like Checkbox etc. Just register the MouseListener or MouseAdapter to a GUI component you would like.

if(e.getClickCount() == 3)

The above code handles triple clicks.

We extended MouseAdapter to override only one method mouseClicked (MouseEvent e) and if MosueListener is implemented, it is required to override all the five methods.

Also learn the handling of mouse right click.

View All Event Handling Examples

For different miscellaneous topics on Java, refer View All Java Examples

Pass your comments and suggestions on this tutorial "Mouse Double Click Java".

Leave a Comment

Your email address will not be published.