|
||||||
| Java Tutorials Tutorials and Code for Java |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Display Modes |
|
|||||
|
Any program that actually does something is event driven. With out events, your program is entirely static and probably does nothing. While some events might be caused by an internal timer, most events are caused by the user. This tutorial will show you how to use the methods given to use my the MouseListener class.
First we are going to create a simple swing GUI. Since this tutorial already assumes you know how to do that, I won't go into details on this subject. Java Code:
Next in the class header we will implement and import the java.awt.event package. Java Code:
Since we are implementing the class, we need to use all the methods provided to us by MouseListener which, in no specific order are: mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), and mouseReleased(). The difference between mouseClicked() and mousePressed()/mouseReleased() are minimal, its just that mouseClicked() is a mouse press and mouse release, which mousePressed() and mouseReleased just listen for the mouse being pressed and released respectively. So after implementing the methods or class looks something like this: Java Code:
The last step we must do is add a mouseListener to an object. Most J-Objects [JLabels, JFrames, JButton, ect...] I am going to add a mouse listener to or main frame "frame." Java Code:
And thats all you need to do. Now since each MouseListener method (mouseClicked, MouseEntered, ect..) is passed a MouseEvent "e" you can expand the capabilities of the methods. For example if you wanted to check which object is being clicked, it might look something like this: Java Code:
__________________
CodeCall Blog | CodeCall Wiki | Shareware | Linux Forum | My Blog Chat with other CodeCall members on IRC; connect to irc.codecall.net and join #codecall |
| Sponsored Links |
|
|
|
|||
|
It might also be interesting to explain its derived adapter class.
The MouseListener interface has an abstract class implementation called MouseAdapter. The advantage of using the adapter class instead of the interface is that when you only need one method (say, mouseClicked, as in the final example), you don't need to implement the other ones. The code, when using MouseAdapter, would then look like this: Java5 Code:
|