How-To's > How do I track mouse coordinates?


Intercept the MouseEvent objects from any Node in the Scene. Use its x and y variables to determine the current mouse location. The following example tracks mouse coordinates as it passes over a Rectangle object (a Node subclass).

package mousetracker;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.layout.Flow;

// Height and Width of this Application
def APP_WIDTH = 500;
def APP_HEIGHT = APP_WIDTH;

// Script variables to track Mouse X and Y Coordinates
var mouseX = 0.0;
var mouseY = 0.0;

// GUI Code
Stage {

    title: "Mouse Tracker"
    scene: Scene {

        content: [ // Begin scene's content

            // Create a rectangle Node to move the mouse over
            Rectangle {
                x: 0 y: 0 width: APP_WIDTH 
                height: APP_HEIGHT 
                fill: Color.WHITE;
                onMouseMoved: function(e: MouseEvent){
                    mouseX = e.x;
                    mouseY = e.y;
                }
            }

            // Add Text objects to convey this info to the user
            Flow {
                width: APP_WIDTH
                content: [Text {content: "Mouse X: "}
                          Text {content: bind mouseX.toString()}
                          Text {content: "Mouse Y: "}
                          Text {content: bind mouseY.toString()}];
            }

        ] // end scene's content
    } // end Scene
} // end Stage

Tips

  • The onMouseMoved variable is defined in the Node class. It is inherited by all Node subclasses, including Rectangle.
  • In addition to onMouseMoved, Node objects encapsulate other mouse-related data, such as onMouseEntered and onMouseExited. You can create functions (as shown in the previous example) to handle the MouseEvent objects for each case.
  • Similarly, MouseEvent objects encapsulate more information than just x and y. Use the MouseEvent API documentation to discover what other mouse-related information is available to your program.
  • This particular application displays its Text objects in a Flow layout. As the mouse moves across the screen (through a Rectangle), it saves the current coordinates to the script variables named mouseX and mouseY. The Text objects bind their content to these variables to keep the GUI in sync with this data.

Examples

  • BrickBreaker
    In this video game, the user's mouse moves the "bat" across the screen. The program tracks mouse events on an ImageView object (also a Node subclass). See the file Level.fx for implementation details.
  • Adding Drag-and-Drop Behavior to Graphics Nodes
    In this demo application, the user drags an object around the screen with the mouse. It defines a custom ImageView subclass named DraggableImage.

API Documentation

Last Updated: April 2010
[Return to How-To's Home]