It is mostly a problem of logic. For example, with the example code, you can limit the number of events to one per frame: if you move the wheel fast enough (or reduce the frame rate), you will see several Mouse moved messages for one Moved! message.
- import java.awt.event.*;
-
- boolean hasMoved;
-
- void setup()
- {
- size(400, 400);
-
- addMouseWheelListener(new MouseWheelListener()
- {
- public void mouseWheelMoved(MouseWheelEvent mwe)
- {
- mouseWheel(mwe.getWheelRotation());
- }
- });
- }
-
- void mouseWheel(int delta)
- {
- println("Mouse has moved by " + delta + " units.");
- hasMoved = true;
- }
-
- void draw()
- {
- background(255);
- if (hasMoved)
- {
- hasMoved = false; // One shot
- fill(#FF0000);
- println(">>> Moved!");
- }
- else
- {
- fill(#00FF00);
- }
- ellipse(width / 2, height / 2, 100, 100);
- }
The problem is that events are disjoint, the system doesn't tell us if they are part of the same wheel move. Actually, it cannot know, if you think about it. Only the user knows if that's one muscle action or several...
But you can make a finer check, by ensuring some time passed between two events: in this case, they can be seen as distinct.
Change on the code above:
- int lastFrame;
- void mouseWheel(int delta)
- {
- println("Mouse has moved by " + delta + " units.");
- if (frameCount - lastFrame > 2) // You can ajust the number, higher to take in account slow scrolls
- {
- // We had a frame without mouse move, we can say it is a new event
- hasMoved = true;
- }
- lastFrame = frameCount;
- }
As written, adjust the constant in the test to allow slow scrolls: half a second (or a quarter) between two scroll actions should be actually a reasonable value.