Matt
Matt

Reputation: 73

MouseListener is not firing fast enough

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.

Upvotes: 7

Views: 5379

Answers (3)

JayBee
JayBee

Reputation: 31

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.

Upvotes: 3

aperkins
aperkins

Reputation: 13114

To expand a little on what @Ricky Clarkson said: MousePressed will fire every time a mouse button is pressed; MouseReleased will fire every time a mouse button is released, and MouseClicked events will fire every time the OS feels that the user is done clicking (i.e. they have clicked enough to overflow the click count or there was enough time from their last click for it to count as the finished click). the user presses and releases the mouse event.

If you want information on a mouse press, then use the MousePressed event. Otherwise, you will get the event of a MouseClicked whenever the OS wants to give it to Java, which can depend greatly on the settings of the system (i.e. how long of a delay is set in the System options - like the Control Panel - to allow for double clicks).

Hope this helps clarify.


Edit: Removed my statements related to the OS information - it seems I was mistaken in my recollection of how this worked. My apologies.

Upvotes: 1

Ricky Clarkson
Ricky Clarkson

Reputation: 2939

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

Upvotes: 19

Related Questions