【问题标题】:JavaFX, mark coordinates on an image with mouse clickJavaFX,通过鼠标单击在图像上标记坐标
【发布时间】:2017-05-04 13:35:01
【问题描述】:

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

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

【问题讨论】:

  • 你的 ImageView 在 AnchorPane 中吗?
  • @MeGoodGuy AnchorPane-> BorderPane-> ScrollPane -> ImageView

标签: javafx imageview coordinates scenebuilder onmouseclick


【解决方案1】:

一种解决方案是将您的图像视图包装在Pane 中,并将适当的形状添加到Pane。 IE。而不是

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

【讨论】:

  • 谢谢先生!我希望你不介意后续问题。之后如何去除标记?如果我写 imgContainer.getChildren().remove(marker);它只会删除后一个。
  • @Heidi 如果你想删除不止一个,你需要跟踪不止一个;例如您可能需要几个实例字段private Circle firstMarker 和private Circle secondMarker。当您创建它们时,根据需要将这些圆圈分配给它们,然后在您需要时将它们都删除。 (更一般地说,如果你有很多,你可能需要List<Circle> 或类似的。)
【解决方案2】:

试试这个:

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

如果你想删除它:

anchorPane.getChildren().remove(c);

是的,就在这个地方

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2013-03-20
    • 1970-01-01
    • 2023-01-30
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多