繁体   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