Image Drag with Mouse in JavaFX
Saturday Nov 29, 2008
So, we got a discussion here. Last week we(me, Subrata and Vikram, both my office colleagues) are discussing about dragging an image with mouse pointer in JavaFX.
So, this was the first code. Point is to drag an image from the same place where we first hit the mouse, like it happens when we drag a folder :
package sample5;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import java.lang.System;
var x: Number;
var y: Number;
var im = Image {
url: "{__DIR__}im2.PNG"
};
var temp1:Number = 0;
var temp2: Number = 0;
var count: Integer = 1;
Stage {
title: "Application title"
width: 250
height: 280
scene: Scene {
content: [
ImageView {
x: bind x - temp1
y: bind y - temp2
image: Image {
url: "{__DIR__}im2.PNG"
}
onMouseDragged: function( e: MouseEvent ):Void {
x = e.x;
y = e.y;
if(count <= 1) {
temp1 = e.x;
temp2 = e.y;
}
count++;
}
}
]
}
}
You can see those patches of counts and flags which makes the code so unstable. And a bug, when you leave the mouse once, it cant grip the image from your mouse point again.
Subrata has written a cleaner code which works correct and here it is :
package mousedrag;import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent;/** * @author Subrata Nath */var imgX : Number = 20; var imgY : Number = 20; var startX : Number; var startY : Number ; var distX : Number; var distY : Number ;Stage { title: "Mouse smooth drag" width: 250 height: 280 scene: Scene { content: [ ImageView { x : bind imgX y : bind imgY image: Image {url: "{__DIR__}Mail.png" } onMousePressed: function( e: MouseEvent ):Void { startX = e.x; startY = e.y; // Calculate the distance of the mouse point from the image top-left corner // which will always come out as positive value distX = startX - imgX; distY = startY - imgY; } onMouseDragged: function( e: MouseEvent ):Void { // Find out the new image postion by subtracting the distance part from the mouse point. imgX = e.x - distX; imgY = e.y - distY; } } ]} }















I actually did this awhile back (in June 2007...
...
Thanks for the info!
Again, Thanks. I have blogged an update :
Thanks Charles and you are welcome too :)
I recently came across your blog and have been rea...
thanks Alanna !