让JavaFX等待并继续执行代码
基本上,我正在尝试使用JavaFX取得简短的效果.我有一个心的形状(由两个圆和一个多边形加在一起),可以使用双精度值p来改变大小. 标准大小"将为p = 1.0;.
Basically I am trying to make a short effect using JavaFX. I have the shape of a heart (added together from two circles and a polygon) that I can vary in size using the double value p. "Standart Size" would be p = 1.0;.
我正在尝试给心脏增加泵送效果.我有方法pumpOnce():
I am trying to add a pumping effect to the heart. I have the method pumpOnce():
public void pumpOnce(){
p = p + 1;
initHeart();
//Here goes what ever it takes to make stuff working!!
p = p - 1;
initHeart();
}
initHeart()根据p吸引心脏.
我发现Thread.sleep();或类似方法由于JavaFX中的线程原理而无法工作.
I have found out that Thread.sleep(); or similar methods will not work due to the thread philosophy in JavaFX.
但是我该怎么用呢?
JavaFX动画可能是可行的方法,但是如果您想自己滚动,JavaFX中的线程原理"并不难处理,或在后台线程中执行其他更复杂的操作.
The JavaFX animations are probably the way to go, but the "thread philosophy" in JavaFX isn't hard to work with if you want to roll your own, or do other, more complicated things in background threads.
以下代码将暂停并更改标签中的值(全面披露,我正在重复使用为另一个问题编写的代码):
The following code will pause and change the value in a label (full disclosure, I'm reusing code I wrote for another question):
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloWorld extends Application {
private static Label label;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
label = new Label();
label.setText("Waiting...");
StackPane root = new StackPane();
root.getChildren().add(label);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
Task<Void> sleeper = new Task<Void>() {
@Override
protected Void call() throws Exception {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
};
sleeper.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
label.setText("Hello World");
}
});
new Thread(sleeper).start();
}
}
基本的JavaFX后台工具是Task,任何实际执行任何操作的JavaFX应用程序都可能到处都是乱七八糟的东西.了解如何使用它们.
The basic JavaFX background tool is the Task, any JavaFX application that actually does anything will probably be littered with these all over. Learn how to use them.