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
onMouseMovedvariable is defined in theNodeclass. It is inherited by allNodesubclasses, includingRectangle. - In addition to
onMouseMoved,Nodeobjects encapsulate other mouse-related data, such asonMouseEnteredandonMouseExited. You can create functions (as shown in the previous example) to handle theMouseEventobjects for each case. - Similarly,
MouseEventobjects encapsulate more information than justxandy. Use theMouseEventAPI documentation to discover what other mouse-related information is available to your program. - This particular application displays its
Textobjects in aFlowlayout. As the mouse moves across the screen (through aRectangle), it saves the current coordinates to the script variables namedmouseXandmouseY. TheTextobjects 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 anImageViewobject (also aNodesubclass). 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 customImageViewsubclass namedDraggableImage.
API Documentation
Last Updated: November 2009
[Return to How-To's Home]
Do you have comments about this article? We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of repliesyour information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.