Introduction
This article will illustrate an application using the MouseListener Interface in NetBeans IDE. It is a pre-defined interface of the java.awt.event.MouseListener package. The MouseListener Interface is used for receiving interesting mouse events like the following:
- Enter
- Exit
- Click
- Press
- Release
The MouseListener interface is used to track the preceding events of the mouse on the area occupied by the graphical component.
MouseListener methods
Since MouseListener is an interface, the body of all the methods of the MouseListener interface must be defined either used or not. There are five MouseListener methods on the various components like Textfield, Button, List and so on. The following methods are used when the event related to the mouse occurs.
- mouseEntered(): This method is used when an event occurs on entry of the mouse on any of the components over the Frame.
Syntax of this method
public void mouseEntered(MouseEvent e){ }
- mouseExited(): This method is used when an event occurs on exit of the mouse on any of the specified components over the Frame.
Syntax of this method
public void mouseExited(MouseEvent e){ }
- mouseClicked(): This method is used when an event occurs on clicking of mouse on any of the specified components over the Frame.
Syntax of this method
public void mouseClicked(MouseEvent e){ }
- mousePressed(): This method is used when an event occurs on the long press of the mouse key on any of the specified components over the Frame.
Syntax of this method
public void mousePressed(MouseEvent e){ }
- mouseRlease(): This method is used when an event related to the release of the mouse key occurs after a long press on any of the specified components over the Frame.
Syntax of this method
public void mouseReleased(MouseEvent e){ }
This application is based only on MouseListener, Frame and a Textfield. The application is, when the mouse pointer enters the Textfield, the textfield moves from its original place.
The source code is as follows:
In the code above, class Random is initialized to provide random coordinates for the placement of the Textfield at various places.
Run The source code
Output
The following window appears as the output of the source code above.
When the mouse pointer enters the Textfield, it moves to a random place. The screenshot is shown below.