devxlogo

Using the onMouseDragged Event in JavaFX

Using the onMouseDragged Event in JavaFX

It’s easy to implement a nice dragging effect in JavaFX, using the onMouseDragged event in conjunction with the bind operator (incremental and lazy evaluation of attributes operator).

import javafx.ui.canvas.*;import javafx.ui.*;import java.lang.System;class CircleDragging extends CompositeNode{attribute lx: Integer;attribute ly: Integer;}CircleDragging.lx = 0;CircleDragging.ly = 0;function CircleDragging.composeNode() =Group {    transform:[]    content:[ Circle {        cx: bind lx        cy: bind ly        radius: 10        fill: red        stroke: black        strokeWidth: 10        onMouseDragged: operation(e:CanvasMouseEvent) {    lx += e.localDragTranslation.x;    ly += e.localDragTranslation.y;     }    }]};Frame {    centerOnScreen: true    visible: true    height: 500    width: 500    title: "JavaFX - CircleDragging"    onClose: operation() {System.exit(0);}    content: ScrollPane {    background: white    view: Canvas {    background: black    cursor: DEFAULT    content: [CircleDragging]    }    }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist