2013-10-02 63 views
3

我有一個節點(ImageView)顯示圖像和另一個節點(矩形),它位於頂部。我需要的行爲是,當鼠標在矩形上拖動(按下 - 拖放手勢)時,兩個節點應該一致地移動。我的思維過程如下:JavaFX2:拖動事件開始和結束座標

•將兩個節點在拖動方向上移動相同的距離。

對於這個選項(也許有更多的選擇)我需要鼠標拖動的開始和結束之間的距離。我嘗試捕獲拖動的開始和結束座標,但未成功。我想我迷失在哪個處理程序中去執行。

我的代碼如下:

import javafx.event.EventHandler; 
import javafx.geometry.Rectangle2D; 
import javafx.scene.image.ImageView; 
import javafx.scene.input.MouseEvent; 

public class MyView 
{ 

    double mouseDragStartX; 
    double mouseDragEndX; 

    double mouseDragStartY; 
    double mouseDragEndY; 

    ImageView imageView; 

    public MyView() 
    { 
     imageView = new ImageView("C:\\temp\\test.png"); 
    } 

    private void setRectangleEvents(final MyObject myObject) 
    { 
     myObject.getRectangle().setOnMousePressed(new EventHandler<MouseEvent>() 
     { 
      @Override 
      public void handle(MouseEvent mouseEvent) 
      { 
       mouseDragStartX = mouseEvent.getX(); 
       mouseDragStartY = mouseEvent.getY(); 
       mouseEvent.consume(); 
      } 
     }); 

     myObject.getRectangle().setOnMouseReleased(new EventHandler<MouseEvent>() 
     { 
      public void handle(MouseEvent mouseEvent) 
      { 
       mouseDragEndX = mouseEvent.getX(); 
       mouseDragEndY = mouseEvent.getY(); 
       myObjectDraggedHandler(); 
      } 
     }); 
    } 

    private void myObjectDraggedHandler() 
    { 

    Rectangle2D viewport = this.imageView.getViewport(); 
    double newX = this.imageView.getImage().getWidth() 
     + (mouseDragEndX - mouseDragStartX); 
    double newY = this.imageView.getImage().getHeight() 
     + (mouseDragEndY - mouseDragStartY); 

     this.imageView.setViewport(new Rectangle2D(newX, newY, viewport.getWidth(),  viewport 
      .getHeight())); 

    } 
} 

P.S:此代碼只是用於指示什麼,我想實現,不會正確編譯。

或者,也許我的問題應該是: 如何捕獲鼠標拖動的長度或跨度?

回答

2

試試這個我認爲這將有助於你

obj.setOnMousePressed(new EventHandler<MouseEvent>() { 
    @Override public void handle(MouseEvent mouseEvent) { 
    // record a delta distance for the drag and drop operation. 
    dragDelta.x = stage.getX() - mouseEvent.getScreenX(); 
    dragDelta.y = stage.getY() - mouseEvent.getScreenY(); 
    } 
}); 
obj.setOnMouseDragged(new EventHandler<MouseEvent>() { 
    @Override public void handle(MouseEvent mouseEvent) { 
     stage.setX(mouseEvent.getScreenX() + dragDelta.x); 
    stage.setY(mouseEvent.getScreenY() + dragDelta.y); 
    } 
}); 
相關問題