Angom
Angom

Reputation: 763

How to make a node move whenever mouse is move over the scene (in JavaFX)?

I have written a small JavaFX program in which a Rectangle node is made to moved whenever mouse cursor is moved over the scene containing the rectangle. Here is my code:

public class MovedObjectWhenMouseMoved extends Application{
double nodeX;
double currentMousePos;
double oldMousePos = 0.0;   
public static void main(String[] arg){
    launch(arg);
}

@Override
public void start(Stage stage) throws Exception {
    final Rectangle rect = new Rectangle(50, 50, Color.RED);
    rect.setX(20);
    rect.setY(20);

    AnchorPane anchorPane = new AnchorPane();
    anchorPane.getChildren().add(rect);
    Scene scene = new Scene(anchorPane,500,500,Color.GREEN);
    stage.setScene(scene);
    stage.show();

    scene.setOnMouseMoved(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent mouseEvent) {

            currentMousePos = mouseEvent.getX();                

            if(currentMousePos>oldMousePos){                    
                rect.setX(rect.getX()+1);  // Move right 
            }else if(currentMousePos<oldMousePos){
                rect.setX(rect.getX()-1); // Move Left
            }

            oldMousePos = currentMousePos;  
        }

    });
  }
}

But here the problem is that the node speed is not same as the mouse speed. How can I rectify this problem? Also please let me know if there is any better approach.

Upvotes: 1

Views: 1111

Answers (1)

Qwertovsky
Qwertovsky

Reputation: 1106

Mouse can change position on more then 1 pixel.

Try this code for handle:

currentMousePos = mouseEvent.getX();
double dX = currentMousePosition - oldMousePos;                
rect.setX(rect.getX() + dX);
oldMousePos = currentMousePos;

Upvotes: 4

Related Questions