java - 如何在不冻结 UI 的情况下休眠代码?
问题描述
所以,我正在开发一个 javafx 应用程序,我正在尝试在场景 1 和场景 2 之间切换,但两者中间都有一个“加载”场景。我试图Thread.sleep()
在切换到场景 2 之前模拟加载屏幕动画,但是动画冻结(是的,我知道这是因为那个线程是“UI 线程”)。
我已经尝试过使用时间表但不起作用,我很新,我可能做错了什么哈哈
我能做些什么?寻找简单的东西。
我的代码:
private void handleButton(ActionEvent event) throws Exception {
if(true){
Node node=(Node) event.getSource();
Stage stage=(Stage) node.getScene().getWindow();
Parent root= FXMLLoader.load(getClass().getResource("LoadingFXML.fxml"));
Scene loading= new Scene(root);
stage.setScene(loading);
stage.show();
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Waiting");
}
}));
timeline.setCycleCount(1);
timeline.play();
root=FXMLLoader.load(getClass().getResource("Scene2FXML.fxml"));
Scene scene2=new Scene(root);
stage.setScene(scene2);
stage.show();
}
}
固定的:
private void handleButton(ActionEvent event) throws Exception {
if(true){
Node node=(Node) event.getSource();
Stage stage=(Stage) node.getScene().getWindow();
Parent root= FXMLLoader.load(getClass().getResource("LoadingFXML.fxml"));
Scene loading= new Scene(root);
stage.setScene(loading);
stage.show();
root=FXMLLoader.load(getClass().getResource("Scene2FXML.fxml"));
Scene scene2=new Scene(root);
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
stage.setScene(scene2);
stage.show();;
}
}));
timeline.setCycleCount(1);
timeline.play();
}
}
解决方案
您的handleButton()
方法在主线程中运行,用于 UI 界面绘制和对用户操作作出反应。
在不同的线程中运行此方法内容。在这种情况下,如果你调用sleep()
,它不会冻结 UI 界面。
推荐阅读
- function - How to write a function that takes a slice of functions?
- jquery - 为什么我会收到此错误:SyntaxError: JSON.parse: unexpected keyword at the line 1 column 1 of the JSON data?
- android - 如果未选择任何字符串,则使用字符串“男性或女性”查询数据库返回所有结果
- java - 在数组中搜索字符串出现的次数
- html - 将查询重定向到搜索结果 API Flask
- python-3.x - 如何提高红色检测的准确性
- c++ - 将“this”传递给 C API 回调,获取 void* 用户数据
- javascript - Discord Bot:在重新加载时不会重置的每个公会变量
- javascript - 将赛季时间表分成几周而不重复球队比赛
- ruby-on-rails - 如何在rails中创建word文档