Select Page

Mouse events are events thrown by the mouse. Mouse events are in two types. We have the MouseListener events and the MouseMotionListener events. The MouseListener handles events created when the mouse is stationary or is not in motion.

MouseListener events are invoked when the mouse is stationary. That is, when the mouse is motionless and stable. This generates events such as mousePressed, mouseReleased, mouseClicked, mouseExited and mouseEntered.

For these events to be realized, an object of the class that holds these methods must be registered with the component you want the events to take place on using the method addMouseListener(). 

import statement for MouseListener interface

If you use the MouseListener interface in your program, you should have the this import statement. This makes the interface available for your program’s use.

MouseListener Declaration

The getX() and getY() methods

The getX() method returns the X coordinate of the mouse when an event occurs. The getY() returns the Y coordinate of the mouse when an event occurs.

Program to demonstrate handling of MouseListener event

Explanation of code

Line 3-8: import statements import a set of classes for use in the program. These include the GridLayout, JPanel, MouseEvemt etc

Line 11-16: Reference variables of some swing components are created to reference their respective objects later in the program

Line 18-19: Two final constants are created in memory. These will be used to set the width and height of the JFrame window

Line 23: The title bar of the JFrame window is set using the setTitle to  “MouseListener Demonstration”