import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class threadTest extends Application{
private String text ="";
@Override
public void start(Stage primaryStage) {
StackPane pane = new StackPane();
Label lbText = new Label("Welcome");
pane.getChildren().add(lbText);
new Thread(new Runnable() {
@Override
public void run() {
try{
while(true){
if(lbText.getText().trim().length()==0)
text = "Welcome!";
else
text = "";
//能发生闪烁的关键,更新应用程序线程中的GUI
Platform.runLater(new Runnable() {
@Override
public void run() {
lbText.setText(text);
}
});
Thread.sleep(400);
//如果在一个循环当中调用了sleep方法,那就应该将这个循环放在try-catch块中
}
}
catch(InterruptedException ex){
}
}
}).start();
// lambda 表达式简化程序中匿名内部类
// new Thread(()->{
// try{
// while(true){
// if(lbText.getText().trim().length()==0)
// text = "Welcome!";
// else
// text = "";
// Platform.runLater(()->lbText.setText(text));
// Thread.sleep(400);
// }
// }
// catch (InterruptedException ex){
// }
// }).start();
Scene scene = new Scene(pane,400,100);
primaryStage.setTitle("Flash");
primaryStage.setScene(scene);
primaryStage.show();
}
}
JAVA基础多线程应用 闪烁的文本和Lamdba表达式实现
最新推荐文章于 2022-01-29 14:16:33 发布