• Post Reply Bookmark Topic Watch Topic
  • New Topic

Mouse input question  RSS feed

 
Terry Flint
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple question here. I'm wondering how to use the getXOnScreen and getYOnScreen methods from the MouseEvent class mentioned here. As far as I understand them, they're supposed to return ints for each of the co-ordinates for where the cursor is at a given pint in time? Is that correct. If so, that seems incredibly useful, but I'm not sure how to actually implement them. I see you can't just employ them by simply importing the MouseEvent class in java.awt, which I had kind of hoped would be the case. I have two classes below designed to display a 400*400 paint window. If possible, could someone give me an example of one of those methods used in this context? If not, any example of them working is fine, as long as a simpleton like me can understand it .



 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need a specific event listener that gets called in a specific cicumstance and receives an instance of MouseEvent.
There are several such listeners, like MouseListener, MouseMotionListener and MouseInputListener, which combines the previous two.
You can learn about Swing event handling in general from this tutorial over at Oracle.
Here's a bit of sample code specific to your example that should get you started:




As you may have noticed the MouseTracker class does not implement any of the interfaces I mentioned earlier. Instead it extends the abstract class MouseAdapter, which implements all mouse related event listeners. The benefit of this is that you can simply override the method you are interested in, instead of have to implement all the methods a particular interface specifies. It keeps the code more compact.

Try playing around with it.
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, when you feel like you have the hang of how event listeners work, you should probably read about Swing concurrency and the Even Dispatch Thread (EDT). The way you are creating the Swing components now is not thread-safe and that is a bug in the program, but I recommend you not worry too much about it at this stage. Keep it in mind though.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!