当我使用JavaFX时,睡眠功能将无法正常工作。像下面的代码一样:
public class Controller {
@FXML private Label label;
@FXML private Button b1;
public void write() throws InterruptedException
{
label.setText("FIRST TIME");
for(int i=1;i<=5;i++)
{
System.out.println("Value "+i);
label.setText("Value "+i);
Thread.sleep(2000);
}
label.setText("LAST TIME");
}
按下按钮b1时,将调用写入功能。现在,在控制台上2秒钟后将打印“ Value + i”。但是那个时候标签l1的文本没有改变,最后只变成了“ LAST TIME”。这里有什么问题?
答案 0 :(得分:3)
在阅读了注释中建议的链接之后,您可能希望从fx线程中删除较长的过程(延迟)。
您可以通过调用另一个线程来实现:
public void write() {
label.setText("FIRST TIME");
new Thread(()->{ //use another thread so long process does not block gui
for(int i=1;i<=6;i++) {
String text;
if(i == 6 ){
text = "LAST TIME";
}else{
final int j = i;
text = "Value "+j;
}
//update gui using fx thread
Platform.runLater(() -> label.setText(text));
try {Thread.sleep(2000);} catch (InterruptedException ex) { ex.printStackTrace();}
}
}).start();
}
或者更好地使用fx动画工具,例如:
private int i = 0; // a filed used for counting
public void write() {
label.setText("FIRST TIME");
PauseTransition pause = new PauseTransition(Duration.seconds(2));
pause.setOnFinished(event ->{
label.setText("Value "+i++);
if (i<=6) {
pause.play();
} else {
label.setText("LAST TIME");
}
});
pause.play();
}
答案 1 :(得分:3)
我会尝试创建用于延迟的新线程。
package sample;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
public class Controller implements Runnable{
private volatile boolean isRunning = false;
private Thread timer;
private int delay = 2000;
@FXML
private Label label;
@FXML
private Button button;
private void start(){
timer = new Thread(this, "timer");
isRunning = true;
timer.start();
}
private void stop(){
isRunning = false;
}
private void interrupt(){
isRunning = false;
timer.interrupt();
}
@Override
public void run() {
int counter = 0;
while (isRunning) {
try {
++counter;
String text = "MyText" + counter;
Platform.runLater(() -> label.setText(text));
if (counter == 5) {
stop();
}
Thread.currentThread().sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
更新Platform.runLater()
下的标签非常重要-JavaFx主线程是唯一允许更新JavaFx对象的线程。