How-To's > How do I create a response to a mouse event?
Version: JavaFX 1.3Any node can listen for and respond to a mouse event. Variables in the Node class are responsible for listening to mouse events. The following two variables are Boolean data types:
hover– Listens for whether the mouse is hovering over the nodepressed– Listens for whether a mouse button has been pressed over the node (by default, the primary mouse button)
In addition, a number of variables in the Node class define a function that is called when particular mouse events occur within the node's boundaries:
onMouseClickedonMouseDraggedonMouseEnteredonMouseExitedonMouseMovedonMousePressedonMouseReleasedonMouseWheelMoved
The event response function has the following syntax:
function (e:MouseEvent):Void {<body>}
The function has one argument of arbitrary name e and type MouseEvent, and no return value. The event response is defined in the body of the function.
Tips
- Mouse event variables are limited to systems that have a mouse. The
Nodeclass also has some variables that listen for keystroke events. - If the node's
fillvariable has the value null, mouse events will not work for the fill, though they will work for the stroke, if there is a non-null stroke value. To enable mouse events with a transparent fill color, use the valuefill: Color.TRANSPARENT.
Example Code 1: hover and pressed Variables
The following code adds a yellow stroke to the square if the mouse hovers over the square. The fill color changes to red if the mouse button is pressed while hovering over the square.

import javafx.scene.*;
import javafx.scene.shape.*;
import javafx.scene.paint.*;
var r : Rectangle;
Scene {
content: [
r = Rectangle {
x: 20 y: 20 width: 50 height: 50
fill: bind if (r.pressed) Color.RED else Color.GREEN
stroke: bind if (r.hover) Color.YELLOW else null
strokeWidth: 10
}
]
}
Example Code 2: onMouseDragged Event
The following is an example of an onMouseDragged event, in which the response is to set the horizontal and vertical coordinates of the rectangle to the position to which it has been dragged.

import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
var X = 75.0;
var Y = 90.0;
Stage {
title: "Application title"
scene: Scene {
width: 200
height: 200
content: [
Rectangle {
x: bind X, y: bind Y
height: 20
width: 20
fill: Color.BLUE
onMouseDragged: function( moveRect: MouseEvent ):Void {
X = moveRect.x;
Y = moveRect.y;
}
}
Text {
content: "Drag the blue square"
x: 35
y:180
}
]
}
}
Examples of Mouse Entered and Mouse Exited:
Examples of Mouse Click, Press, Drag, Release (Common Profile), Enter and Exit (Desktop Profile)
Examples of Mouse Press, Move, Click (Common Profile), Exit (Desktop Profile)
Examples of Mouse Hover
API Documentation
Related How-To Topics
Last Updated: April 2010
[Return to How-To's Home]