Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java mouse events ignored when mouse is moving?

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.)

like image 501
Ryan Avatar asked Jan 20 '12 03:01

Ryan


1 Answers

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.

like image 115
Russell Zahniser Avatar answered Oct 21 '22 17:10

Russell Zahniser