JavaFX保存可拖动节点

时间:2016-06-15 23:27:54

标签: javafx drawing drag

构建一个javaFX应用程序,从数据库中获取矩形的位置,宽度和深度,以便根据实际窗格宽度和深度绘制数据库包含矩形posX,posY,width和depth,我能够绘制根据我在本地绘制的窗格的矩形,问题是,当拖动矩形时,不知道如何使用新值更新数据库,因为我应该将它们转换回实际的协调,代码:

// resourcePosX,resourcePosY,resourceDepth and resourceWidth are the actual
// rectangle dimensions from the database
//  actualDepth and actualWidth are the actual pane dimensions
// prefWidth and prefHight are the current pane dimensions that i am drawing on 
int posX = (resourcePosX*this.prefHight)/actualDepth;
int posY = (resourcePosY*this.prefWidth)/actualWidth;

int depth = (resourceDepth*this.prefHight)/actualDepth;
int wedth = (resourceWidth*this.prefWidth)/actualWidth;

Node resource= new Rectangle(posX, posY, depth, wedth);
EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent t) {
                orgSceneX = t.getSceneX();
                orgSceneY = t.getSceneY();
                orgTranslateX = ((Node) (t.getSource())).getTranslateX();
                orgTranslateY = ((Node) (t.getSource())).getTranslateY();
            }
        };

        EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent t) {
                double offsetX = t.getSceneX() - orgSceneX;
                double offsetY = t.getSceneY() - orgSceneY;
                double newTranslateX = orgTranslateX + offsetX;
                double newTranslateY = orgTranslateY + offsetY;

                ((Node) (t.getSource())).setTranslateX(newTranslateX);
                ((Node) (t.getSource())).setTranslateY(newTranslateY);
            }
        };

        resource.setOnMouseDragged(onMouseDraggedEventHandler);


        resource.setOnMousePressed(onMousePressedEventHandler);

如何将矩形当前x和y再次转换为实际?为了将它们保存在数据库中。

使用画布会更容易还是更好?因为到目前为止我对画布一无所知

1 个答案:

答案 0 :(得分:1)

您可以创建setOnMouseReleased鼠标处理程序并使用fixPostion()方法,该方法使用当前位置加上翻译位置计算当前位置。

EventHandler<MouseEvent> onMouseReleasedEventHandler = new EventHandler<MouseEvent>() {

  @Override
  public void handle(MouseEvent t) {

    fixPosition((Node) t.getSource());

  }
};

resource.setOnMouseReleased(onMouseReleasedEventHandler);

private void fixPosition( Node node) {

    double x = node.getTranslateX();
    double y = node.getTranslateY();

    node.relocate(node.getLayoutX() + x, node.getLayoutY() + y);

    node.setTranslateX(0);
    node.setTranslateY(0);

}