Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MouseListener is not firing fast enough

Tags:

java

swing

awt

I have a Class extending JFrame that is watching for a mouse click anywhere:

addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e){
        System.out.println("mouse was clicked");
    }
});

I usually have to wait nearly a second between clicks to trigger the event. If I make 2 or 3 clicks in a second, only one event fires. How do you watch for fast click events?

This is my first time using Java and I'm using NetBeans.

like image 549
Matt Avatar asked Sep 03 '10 19:09

Matt


People also ask

What is the difference between MouseListener and MouseMotionListener?

We can implement a MouseListener interface when the mouse is stable while handling the mouse event whereas we can implement a MouseMotionListener interface when the mouse is in motion while handling the mouse event.

What is the purpose of MouseListener interface?

Interface MouseListener (To track mouse moves and mouse drags, use the MouseMotionListener .) The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest).

What is MouseAdapter vs MouseListener in Java?

MouseListener is an Interface and MouseAdapter is an implementation of that. You can use the MouseAdapter in every place that you use a MouseListener. But implementations have details that have be take in count.


2 Answers

Try using mousePressed instead of mouseClicked. mouseClicked looks for multiple button clicks, so it will coalesce some events.

like image 192
Ricky Clarkson Avatar answered Sep 19 '22 03:09

Ricky Clarkson


Hopefully this helps 3.5 years later for anyone searching for answers to the same problem :)

When you click on the mouse you will fire the following events.

  1. MousePressed
  2. MouseDragged (if you pressed hard enough to move the cursor slightly)
  3. MouseReleased
  4. MouseClicked

I ran into this very problem making the events the lazy way in Netbeans using their Forms utility. I found the accidental dragging of my mouse between Press and Release is what killed the click event. Working as intended or a minor failing of the JVM and Netbeans? I don't know.


The work-around I used was to register a MousePressed and MouseReleased event to simulate the clicking. If the Press and Release do not happen on the same Object, MouseReleased will do nothing.

If the Press and Release happen on the same Object, I call my method with appropriate parameters to consume the event.

Note that since I'm handling clicks on the JFrame, so it IS the only swing object, so I'm passing a Point object of the mouse coords and comparing both, ensuring they fall within the specified rectangle.

like image 31
JayBee Avatar answered Sep 19 '22 03:09

JayBee