Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to keep the mouse in center of a node when the Node is Dragged.

923153Mar 24 2012 — edited Mar 24 2012
I am creating a application in which I need to perform many Dragging and Dropping a node at any position in the boundary of the Scene and on top of other nodes.

I have no problem in doing drag and drops my main problem is that the drag is not looking nice.

Consider the code:
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;

public class Number extends Group {
	protected int number;
	
	public Number(int num){
		Rectangle rct = RectangleBuilder.create().arcHeight(5).fill(new Color(0, 0, 0, .5)).arcWidth(5).width(40).height(40).layoutX(0).layoutY(0).build();
		Text text = TextBuilder.create().x(15).y(25).font(Font.font("catull", 20)).text(String.valueOf(num)).fill(Color.GREEN).build();
		getChildren().addAll(rct,text);
		setOnMouseDragged(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent e) {
				
				Scene scene = getScene();
				double x = e.getSceneX();
				double y = e.getSceneY();
				if(x>0 && x<(scene.widthProperty().get() - 40)&& y>0 && y<(scene.heightProperty().get() - 40)){
					setLayoutX(x );
					setLayoutY(y );
				}	
			}
		});
		number = num;
	}
	

}
In the above code when I click in (or near) the center of the node an drag it to a different position, the node automatically moves and positions its LayoutX and LayoutY (its origin) just below the mouse cursor and that is obvious from the above code.

What should I write so that the mouse cursor stays on the same position over the node (or at least at the center of the node ) from the beginning and ending of the drag??.

Edited by: gaurav.suse on Mar 25, 2012 12:23 AM

Edited by: gaurav.suse on Mar 25, 2012 12:25 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 21 2012
Added on Mar 24 2012
0 comments
220 views