Monday, May 31, 2010

Build your very own Mouse Trap Application

This is a very simple yet interesting concept. I had been seeing such applications being developed right from school kids to working professionals using Microsoft technology for the past few years and wondered how to make it possible in Java. I was actually surprised to know that API’s for controlling mouse cursor had been there in Java since JDK 1.3. Well this shows that nothing is impossible in Java,.....Can anyone deny that...haha.

Now let’s move on exploring this concept step-by-step.

  1. Create a simple User Interface as shown below with 1 JButton. The JButton will used with an action “(System.exit(0))” once the cursor gets trapped within the frame.
  2. Use a MouseListener event on the JPanel and override the mouseExited() Method.
  3. The”if” statement in the OnMouseExit event is used to check if the cursor has went beyond the geographical boundaries of the JFrame. (This validation is done because even if the mouse touches the JButton, it will invoke the JPanel’s OnMouseExit Event).
  4. The next line after the “if” statement shows the usage of Robot API (An API used to control mouse and keyboard automatically. This API was introduced in JDK 1.3).
  5. The Robot API’s moveMouse method will move the cursor according to the X and Y axis that we set. (Here I’ve used the centre point of the JFrame ) .



Author: Thiagu