Java MouseListener

This tip is directed primarily to all of our relatively new Java programmers out there. The tip includes a Java applet which demonstrates mouse-handling events, including mouseEntered and mouseExited (that is, the applet does something when the mouse cursor enters a component, and it does something when the mouse cursor leaves the area of the component).

Click here to run the sample applet

Click here to see the actual Java code for the applet.



Step by Step

  1. In the sample applet, mouse-related actions are specified for several of the components on the screen. When you enter any of the textfield areas on the screen, context-sensitive help is displayed in the textarea at the bottom of the applet.

    The code below shows the code that was used for the first textfield object, the textfield in which the user enters the monthly contribution. In the code, a MouseListener is registered for the oMonthly TextField object. A mouseEntered() method is written to handle the action to be performed when the mouse cursor enters the area of this TextField object. A mouseExited() method is written to handle the action to be performed when the mouse cursor leaves the area of this TextField object.


    
    TextArea oHelp=new TextArea(3,400);                 // instantiate a textarea object
    add(oHelp);                                         // add it to the layout manager
    
    TextField oMonthly=new TextField(7);                // instantiate textfield object 7 characters wide
    add(oMonthly);                                      // add the textfield object to the layout manager
    
    oMonthly.addMouseListener(new MouseAdapter()        // add mouse event handlers
    {
      public void mouseEntered(MouseEvent e)	    // mouseEntered event handler
      {
        oHelp.setText("How much money will you contribute to your savings plan each month? Do not use dollar signs or commas.");
      }
      public void mouseExited(MouseEvent e)		    // mouseExited event handler
      {
        oHelp.setText("");
      }
    });						    // be sure to close parentheses and line of code with semi-colon
    
    





Please let us know if this tip has been helpful. Email to rpearson@cobilan.msstate.edu.
Date posted: 05/08/00