I'm trying to update my JavaFX GUI after every 1 second using Task concuurency. I've icons 1.png
, 2.png
, 3.png
and so on. I'm using a while loop increments i++
. I want to display those icons after every 1 second. I don't know how to update Image. I'm using label.setGraphic()
method. 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>
.
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:
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. Please read the provided docs for more information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.