如何在鼠标移动到场景时(在JavaFX中)使节点移动?

时间:2013-12-24 09:21:24

标签: java javafx javafx-2 javafx-8

我编写了一个小型JavaFX程序,只要鼠标光标移动到包含矩形的场景上,就会移动一个Rectangle节点。这是我的代码:

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

    });
  }
}

但问题是节点速度与鼠标速度不同。 我该如何纠正这个问题?如果有更好的方法,也请告诉我。

1 个答案:

答案 0 :(得分:4)

鼠标可以在1个像素以上改变位置。

试试handle的代码:

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