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:
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.
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
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. class a extends Frame implements MouseListener {
  5. TextField t;
  6. Random and = new Random();
  7. public a() {
  8. setLayout(new FlowLayout());
  9. t = new TextField(10);
  10. add(t);
  11. t.addMouseListener(this);
  12. setTitle("Catch The Textfield");
  13. setBackground(Color.pink);
  14. }
  15. public void mouseEntered(MouseEvent e) {
  16. t.setBounds(and.nextInt(400), and.nextInt(400), 90, 20);
  17. }
  18. public void mouseExited(MouseEvent e) {}
  19. public void mouseClicked(MouseEvent e) {}
  20. public void mousePressed(MouseEvent e) {}
  21. public void mouseReleased(MouseEvent e) {}
  22. }
  23. class Mouse {
  24. public static void main(String arg[]) {
  25. a f = new a();
  26. f.setSize(400, 400);
  27. f.setVisible(true);
  28. }
  29. }
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
fig5.2.jpg
Output
The following window appears as the output of the source code above.
MouseListener in Java
When the mouse pointer enters the Textfield, it moves to a random place. The screenshot is shown below.
MouseListener in Java