【问题标题】:Trying to change url of image(FXML) in controller class (javafx)尝试更改控制器类 (javafx) 中图像 (FXML) 的 url
【发布时间】:2020-06-03 19:47:01
【问题描述】:

如何使用我的控制器更改 FXML 文件中标签中的 url。

图像嵌套在窗格 > childeren > Imageview > image 看图

我想要什么

我想遍历图像以检查坐标并使用正确的坐标更改 url。

这是我的循环

for (int i=0; i < 54; i++) {
    if (objectsPane.getChildren().get(i).getLayoutX() == village.getX() && objectsPane.getChildren().get(i).getLayoutY() == village.getY()) {
        objectsPane.getChildren().get(i). // Setting the url
    }

}

如何做到这一点?

【问题讨论】:

  • 无法更改现有图片的网址:您需要为ImageView设置新图片:settlement1.setImage(new Image(...))
  • 我有 54 个 ImageView,我不想在其中使用 id。
  • 最好在控制器中创建它们,而不是在 FXML 中。然后你可以把它们放在List,或者任何最方便的数据结构中。
  • 我还不太明白你的意思
  • 在 FXML 中创建所有这些图像视图非常冗长且重复,因为 FXML 没有循环。在控制器中创建它们,而不是在 Java 代码中,因为您可以使用循环和数据结构,如 Lists 来轻松管理它们。,

标签: java for-loop javafx fxml


【解决方案1】:

首先您需要进行类型转换,因为objectsPane.getChildren().get(i) 为您提供ImageView 类型Node。然后,您可以使用新 url 创建一个新图像。正如詹姆斯评论的那样,不可能只更改网址。最后,您将旧图像替换为新图像。然后,您的代码可能看起来像这样:

for (int i = 0; i < 54; i++) {
    if (objectsPane.getChildren().get(i).getLayoutX() == village.getX() && objectsPane.getChildren().get(i).getLayoutY() == village.getY()) {

        // Type cast from Node to ImageView:
        ImageView imageView = (ImageView) objectsPane.getChildren().get(i);

        // Create new image with new url:
        Image image = new Image(getClass().getResourceAsStream("/assets/img/gameobjects/new-image.png"));

        // Replace the old with the new image:
        imageView.setImage(image);

        // Or alternatively as a one-liner:
        //((ImageView) objectsPane.getChildren().get(i)).setImage(new Image(getClass().getResourceAsStream("/assets/img/gameobjects/new-image.png")));
    }
}

【讨论】:

  • 当我这样做时,我放置了一个我想要的村庄,但是当我在同一个 ImageView 上再次这样做以用不同的图像覆盖它时它不起作用。村庄没有改变。
  • 应该可以用同样的方式一遍又一遍地改变图像。
  • 您的权利。我没有意识到我更改了布局,因此它找不到要再次更改的图像视图。
猜你喜欢
  • 1970-01-01
  • 2013-12-25
  • 2012-12-15
  • 2015-05-29
  • 2013-03-04
  • 2012-09-14
  • 2013-07-22
  • 2018-09-15
相关资源
最近更新 更多