Java mouse events ignored when mouse is moving?
Asked Answered
G

2

9

I've been working on a 2d game in java recently, and am currently trying to get the event-handling system working right. I was trying to get a mouse click to start an animation, and it worked until I tried moving the mouse while clicking. At this point nothing happens at all. I am using both mouselistener and mousemotionlistener classes, and the problem still persists. Here's the code from Main:

public class ML extends MouseAdapter{
   public void mouseClicked(MouseEvent m){
       if(m.getButton()==MouseEvent.BUTTON1)
       guns.playOnce();
   }
   public void mouseReleased(MouseEvent m){
       if(m.getButton()==MouseEvent.BUTTON1);
   }

It calls the animator class to play the set of images one time and stop. The animator was working perfectly before I included mouse events. I can't figure out why it wouldn't work during mouse movement if there is no specified action to perform during that mouse movement. (If there is an obvious solution, I apologize, I started java not too long ago.)

Groce answered 20/1, 2012 at 3:52 Comment(0)
A
7

In Java, a mouse click only registers if the mouse is pressed and released without moving the mouse at all. This is difficult for most users to accomplish, so most UI elements (like buttons) react to the mouse press and release events and ignore the "click".

For a button, though, a better option is to add an ActionListener to it. Then the button itself will listen to the mouse events and decide when it has been clicked.

Armipotent answered 20/1, 2012 at 3:56 Comment(2)
Thanks! The tip about clicking will save me some frustration later.Groce
@trashgod: Well, actually the ButtonModel just tracks the state - it's the ButtonUI that listens for mouse events and updates the model.Armipotent
P
0

Alright, I may be late to the party but I found some workarounds:

If you use either the mousePressed (or the mouseReleased, similar results) event instead, it'll work as you intended. Everything in the code stays the same, expect the method name and the super.mousePressed(e); call;

Procto answered 4/12, 2021 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.