簡體   English   中英

試圖在 controller class 中更改圖像(FXML)的 url(javafx)

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

如何使用我的 controller 更改 FXML 文件中標簽中的 url。

圖像嵌套在窗格 > childeren > Imageview > 圖像見圖片

我想要的是

我想遍歷圖像以檢查坐標並使用正確的坐標更改 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
    }

}

如何做到這一點?

首先,您需要進行類型轉換,因為objectsPane.getChildren().get(i)為您提供ImageView類型的Node 然后您可以使用新的 url 創建新映像。 正如 James 評論的那樣,不可能只更改 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")));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM