2017-05-04 182 views
0

我想在JavaFX中使用一个ImageView上的测量工具,点击图像中的两个点,然后获取它们之间的距离 - 我已经想通了一部分。但是,我也希望能够看到/标记所点击图像上的哪个位置,但我无法想象如何才能最好地实现这一点。我将附上测量工具的代码,以便您更好地了解我正在处理的内容。我认为它必须在第一个if循环里面,我可以在(secondposx,secondposy)中设置标记 - 但是我的问题是,我怎样才能做出这个标记?你有什么好主意吗? :-)JavaFX,用鼠标点击图像上的坐标

private void btnMeasureAction(ActionEvent event) { 
    if (btnMeasure.isSelected()) { 
     imgView.setCursor(Cursor.CROSSHAIR); 
     imgView.setPickOnBounds(true); 
     imgView.setOnMouseClicked(e -> { 
      secondposx = e.getX(); 
      secondposy = e.getY(); 
// I think the MARK should be set here. 
       //System.out.println(secondposx + ", " + secondposy); 


      if ((firstposx == 0)) { 
       firstposx = secondposx; 
       firstposy = secondposy; 
       //System.out.println(firstposx + ", " + firstposy); 
      } else { 
       double distance = Math.sqrt(Math.pow((secondposx - firstposx), 2) + Math.pow((secondposy - firstposy), 2)); 
       System.out.println("The distance is: " + distance); 
       btnMeasure.setSelected(false); 
       imgView.setOnMouseClicked(null); 
       imgView.setCursor(Cursor.DEFAULT); 
       firstposx = 0; 
       firstposy = 0; 
       secondposy = 0; 
       secondposx = 0; 
      } 
+0

是您的ImageView内AnchorPane吗? – MeGoodGuy

+0

@MeGoodGuy AnchorPane-> BorderPane-> ScrollPane - > ImageView – Heidi

回答

2

一种解决方案是包装Pane中的图像视图,并将相应的图形添加到Pane。即而不是

scrollPane.setContent(imgView); 

Pane imgContainer = new Pane(imgView); 
scrollPane.setContent(imgContainer); 

,然后做

Circle marker = new Circle(secondposx, secondposy, 2, Color.SALMON); 
imgContainer.getChildren().add(marker); 

如果你想直接添加标记到现有AnchorPane(或这是祖先的任何其他容器图像视图),并避免创建额外的容器,您可以这样做,但您需要将图像视图中的坐标更改为该容器。您可以先执行此操作,获取场景中的坐标,然后从场景坐标更改为容器坐标:

Point2D sceneCoords = new Point2D(e.getSceneX(), e.getSceneY()); 
Point2D anchorPaneCoords = anchorPane.sceneToLocal(sceneCoords); 
Circle marker = new Circle(anchorPaneCoords.getX(), anchorPaneCoords.getY(), 2, Color.CORAL); 
anchorPane.getChildren().add(marker); 
+0

谢谢先生!我希望你不要介意后续问题。事后如何删除标记?如果我写imgContainer.getChildren()。remove(marker);它只会删除后者。 – Heidi

+1

@Heidi如果你想删除它们中的多个,你需要跟踪它们中的多个;例如你可能需要一些实例字段'private Circle firstMarker'和'private Circle secondMarker'。根据需要,在创建时将这些圆圈分配给这些圆圈,然后在需要时将其移除。 (更一般地说,如果你有很多,你可能需要一个'List '或类似的。) –

1

试试这个:

Circle c = new Circle(secondposx, secondposy, 5, Color.RED); 
anchorPane.getChildren().add(c); 

然后如果u想删除它:

anchorPane.getChildren().remove(c); 

是的它在这个地方