简体   繁体   English

试图在 controller class 中更改图像(FXML)的 url(javafx)

[英]Trying to change url of image(FXML) in controller class (javafx)

How to change the url thats in the tag in the FXML file with my controller.如何使用我的 controller 更改 FXML 文件中标签中的 url。

The Image is nested in pane > childeren > Imageview > image see picture图像嵌套在窗格 > childeren > Imageview > 图像见图片

What I want我想要的是

I want to loop through the imagevies to check the coordinates and with the right coordinate change the url.我想遍历图像以检查坐标并使用正确的坐标更改 url。

This is my loop这是我的循环

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
    }

}

How to achieve this?如何做到这一点?

First of all you need to do a type casting, because objectsPane.getChildren().get(i) gives you the ImageView as of the type Node .首先,您需要进行类型转换,因为objectsPane.getChildren().get(i)为您提供ImageView类型的Node Then you can create a new image with the new url.然后您可以使用新的 url 创建新映像。 As James commented, it is not possible to just change the url.正如 James 评论的那样,不可能只更改 url。 Finally you replace the old image with the new one.最后,您将旧图像替换为新图像。 Your code could then look something similar like this:您的代码可能看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM