获取拖动节点的当前位置

时间:2019-03-27 11:57:20

标签: java javafx coordinates mouse

此代码允许节点在按住鼠标的同时移动:

private double xc, yc;
private void makePortable(Node node){
    node.setOnMousePressed(event -> {
        xc = node.getTranslateX() - event.getSceneX();
        yc = node.getTranslateY() - event.getSceneY();
    });
    node.setOnMouseDragged(event -> {
        node.setTranslateX(xc+event.getSceneX());
        node.setTranslateY(yc+event.getSceneY());
    });
}

此方法内置于单例中。它具有一种将节点转移到的方法,该方法已添加到“窗格”中,并且以前可以移植。

public static final Word WORD = new Word();

private Pane input;
private Text text; 

private Word(){
}

public void init(Pane input){
    this.input = input;
}

public void addCanvas(Text text){
    this.text = text;
    makePortable(text);
    input.getChildren().add(text);
}

public void draw(){
    //And here I need to get his current coordinates
    action(text.get???X(), text.get???Y()); 
}

但是现在我需要获取偏移节点的坐标。我该怎么办?

1 个答案:

答案 0 :(得分:0)

问题尚未解决,但我找到了解决方法。如果您需要在Canvas上打一个结并将其画出来,则首先需要Pane(我建议StackPaneCanvas上加上一个结。 / p>

接下来,您需要截屏Node,并将此截屏上传到Canvas。代码:

public void loadImage(Image image) {
    canvas.getGraphicsContext2D().drawImage(image,
            0, 0, canvas.getWidth(), canvas.getHeight());
}

public void action(){
    WritableImage wi = new WritableImage((int)canvas.getWidth(),
            (int)canvas.getHeight());
    pane.snapshot(null, wi);
    loadImage(wi);
}

Pane的末尾,删除传入的Node。祝好运! (: