簡體   English   中英

使用javafx並發任務將Label屬性綁定到Image屬性<Void>

[英]Binding Label property to Image property using javafx concurrency Task<Void>

我正在嘗試使用Task concuurency每1秒更新一次我的JavaFX GUI。 我有圖標1.png2.png3.png等。 我正在使用while循環遞增i++ 我想每1秒顯示一次這些圖標。 我不知道如何更新圖像。 我正在使用label.setGraphic()方法。 我不知道如何在這里使用綁定屬性。 我可能完全錯了。 請幫我。

@Override
public void start() {
  ...
  image = new Image(getClass().getResourceAsStream("images/1.png"));
  imv=new ImageView(image);
  label1 = new Label();
  label1.setGraphic(imv);
  monitor(); //A SEPARATE METHOD CONTAINING TASK CODE
  ...
  new Thread(task1).start();
}

...
public void monitor() {
  task1=new Task<Void>() {
    @Override
    protected Void call() {
      int i=1;
      while(true) {
        try {
          Thread.sleep(1000);
          updateMessage(""+i+".png");
          System.out.println("i: "+i);
        }
        catch(Exception e) {
        }
        i++;
        }
     }
  };
  label1.textProperty().bind(task1.messageProperty());
  ...
}

錯誤是您無法將ReadOnlyStringProperty綁定到ObjectProperty<Image>

您應該在任務消息屬性( docs )中添加一個更改偵聽器( docs )並創建一個圖像,然后將其應用於圖像視圖:

public void monitor() {
    task1 = new Task<Void>() {
        @Override
        protected Void call() {
            System.out.println("run called");
            int i = 1;
            while (true) {
                try {
                    Thread.sleep(1000);
                    updateMessage(i + ".png");
                    System.out.println("i: " + i);
                } catch (Exception e) {

                }
                i++;
            }
        }
    };
    task1.messageProperty().addListener((observable, oldValue, newValue) -> {
        System.out.println(newValue);
        Image image = new Image(getClass().getResourceAsStream("images/" + newValue));
        imv.setImage(image);
    });
}

編輯:

給定片段中的Lambda表達式表示ChangeListener 請閱讀提供的文檔以獲取更多信息。

暫無
暫無

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

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