Activity 7.2 - Constructing a window capable of knowing when the mouse is over it

Topic

In this activity we use a mouse listener and a key listener.

Task

You are asked to write an application which will display a window capable of detecting when the mouse pointer is over it.

The window should be a frame of dimensions 400 by 100, located at (100, 100), on which is placed a JTextField field. The frame title should be "Mouse sensor". When the program is first run the text field should show the message "Waiting for mouse activity".

A small window showing the text "Waiting for mouse activity."

A mouse listener is attached to the text field. If the mouse pointer moves over the text field (mouse entered) the listener should cause the message to change.

A small window showing the text "I sense the presence of a mouse."

If the mouse pointer leaves the text field (mouse exited) the listener should recognise this.

A small window showing the text "That mouse has gone now.
Press Enter to reset this window."

A key listener is also attached to the text field. When Enter is pressed this listener should reset the message.

A small window showing the text "Waiting for mouse activity."

Instructions

  1. Create a new project called MyEx7_2 in the Unit 7 folder. In the New Java Application wizard name the Main Class myex7_2.MouseSensorTest.
  2. Taking the class KeyFrame from the unit as a guide, write a new class MouseSensor which defines a frame that will behave as described above. You may wish to look at the example of NewMouser for guidance.
  3. Complete the main class MouseSensorTest so it creates an instance of MouseSensor and makes it visible. Compile and test your program.
  4. For our sample solution see the Solution file.