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]    }    }}

devx-admin

Share the Post: