Posts Tagged ‘measure’


10.15.2008 / Finding the nearest component in Flex

In Flex, we sometimes need to find the component nearest to the mouse cursor. The following example will show you how to do so. Here are the basic steps:

  1. We will set up an event listener to watch for mouse movements.
  2. On every mouse movement, we will loop through all the application’s children, evaluating each one.
  3. We retrieve the bounding rectangle for the component we are currently evaluating.
  4. If the cursor is to the left or right of the component, we find the distance between the x position of the cursor and the x position of the nearest vertical side of the bounding rectangle. If it’s not to the left or the right, the horizontal distance is zero.
  5. If the cursor is above or below the component, we find the distance between the y position of the cursor and the y position of the nearest horizontal side of the bounding rectangle. If it’s not to the top or the left, the vertical distance is zero.
  6. We use the Pythagorean theorem to find the actual distance between the cursor and the component using the two distances previously determined.
  7. If it is a shorter distance to the component we are evaluating than the distance to any of the components previously evaluated, we’ll make note of it.
  8. Finally, we report the closest component found.

…I want more!