[英]Binding Label property to Image property using javafx concurrency Task<Void>
I'm trying to update my JavaFX GUI after every 1 second using Task concuurency. 我正在尝试使用Task concuurency每1秒更新一次我的JavaFX GUI。 I've icons
1.png
, 2.png
, 3.png
and so on. 我有图标
1.png
, 2.png
, 3.png
等。 I'm using a while loop increments i++
. 我正在使用while循环递增
i++
。 I want to display those icons after every 1 second. 我想每1秒显示一次这些图标。 I don't know how to update Image.
我不知道如何更新图像。 I'm using
label.setGraphic()
method. 我正在使用
label.setGraphic()
方法。 I don't know how to use bind property here. 我不知道如何在这里使用绑定属性。 I may be stark wrong.
我可能完全错了。 Please help me.
请帮我。
@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());
...
}
The error is that you can not bind a ReadOnlyStringProperty
to an ObjectProperty<Image>
. 错误是您无法将
ReadOnlyStringProperty
绑定到ObjectProperty<Image>
。
You should add a change listener ( docs ) to the task message property ( docs ) and create an image which you then apply to your image view: 您应该在任务消息属性( 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);
});
}
EDIT: 编辑:
The ChangeListener
is represented by that Lambda expression in the given snippet. 给定片段中的Lambda表达式表示
ChangeListener
。 Please read the provided docs for more information. 请阅读提供的文档以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.