JavaFX Samples
JavaFX Samples

Animated Cursor


Note: this application is self-signed because getting the mouse position is prohibited in the sandbox.

Script

animatedCursor.fx

import java.awt.MouseInfo;
import java.awt.PointerInfo;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

// positions of cursor images
var previousX: Number[] = [-10000, -10000, -10000, -10000, -10000];
var previousY: Number[] = [-10000, -10000, -10000, -10000, -10000];

// images that chase the mouse pointer
var images: ImageView[] = for (i in [4..0 step -1]) {
    ImageView {
        x: bind previousX[i]
        y: bind previousY[i]
        image: Image {
            url: "{__DIR__}duke{i}.gif"
        }
    }
};

var stage = Stage {
    title: "Animated Cursor Sample"
    scene: Scene {
        width: 300
        height: 300
        content: [
            Rectangle {
                // displaying image instead of cursor
                cursor: Cursor.NONE
 
                x: 20 y: 20
                width: 260 height: 260
                fill: Color.AQUAMARINE

                onMouseExited: function(event: MouseEvent) {
                    // when mouse pointer moves out of the application area,
                    // show images
                    for (image in images) {
                        image.visible = false;
                    } 
                }

                onMouseEntered: function(event: MouseEvent) {
                    // when mouse pointer moves into the application area,
                    // hide images
                    for (image in images) {
                        image.visible = true;
                    } 
                }
            },
            images
        ]
    }
}

var timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames: [
        KeyFrame {
            // call action every 100ms
            time: 100ms
            
            action: function() {
                // get the position of mouse pointer
                var point:PointerInfo = MouseInfo.getPointerInfo();
                var x: Number = point.getLocation().x;
                var y: Number = point.getLocation().y;

                // caliculate the local position from the global position
                x = x - stage.x - stage.scene.x;
                y = y - stage.y - stage.scene.y;

                // update images positions
                insert x before previousX[0];
                delete previousX[5];
                
                insert y before previousY[0];
                delete previousY[5];
            }
        }
    ]
};

// Start the animation.
timeline.play();