JavaFX任务可能是解决之道。它们提供了一种在后台执行长时间运行的任务而不冻结用户界面的方法。
这是您可以尝试的示例:
package Demo;import javafx.application.Application;import javafx.concurrent.Task;import javafx.concurrent.WorkerStateEvent;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.geometry.Insets;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.ProgressBar;import javafx.scene.layout.VBox;import javafx.stage.Stage;import javafx.stage.StageStyle;public class BackgroundWorkerDemo extends Application { private final static String CNTR_LBL_STR = "Counter: "; private int counter; Label counterLabel; Button counterButton; Button taskButton; @Override public void start(Stage primaryStage) { counter = 0; counterLabel = new Label(CNTR_LBL_STR + counter); counterButton = new Button("Increment Counter"); counterButton.setonAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { counter++; counterLabel.setText(CNTR_LBL_STR + counter); } }); taskButton = new Button("Long Running Task"); taskButton.setonAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { runTask(); } }); VBox mainPane = new VBox(); mainPane.setPadding(new Insets(10)); mainPane.setSpacing(5.0d); mainPane.getChildren().addAll(counterLabel, counterButton, taskButton); primaryStage.setScene(new Scene(mainPane)); primaryStage.show(); } private void runTask() { final double wndwWidth = 300.0d; Label updateLabel = new Label("Running tasks..."); updateLabel.setPrefWidth(wndwWidth); ProgressBar progress = new ProgressBar(); progress.setPrefWidth(wndwWidth); VBox updatePane = new VBox(); updatePane.setPadding(new Insets(10)); updatePane.setSpacing(5.0d); updatePane.getChildren().addAll(updateLabel, progress); Stage taskUpdateStage = new Stage(StageStyle.UTILITY); taskUpdateStage.setScene(new Scene(updatePane)); taskUpdateStage.show(); Task longTask = new Task<Void>() { @Override protected Void call() throws Exception { int max = 50; for (int i = 1; i <= max; i++) { if (isCancelled()) { break; } updateProgress(i, max); updateMessage("Task part " + String.valueOf(i) + " complete"); Thread.sleep(100); } return null; } }; longTask.setonSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { taskUpdateStage.hide(); } }); progress.progressProperty().bind(longTask.progressProperty()); updateLabel.textProperty().bind(longTask.messageProperty()); taskUpdateStage.show(); new Thread(longTask).start(); } public static void main(String[] args) { launch(args); }}
如果您知道任务将包含多少部分,则此版本将更新任务完成情况。如果没有,请注释更新进度的行中的行,您将获得不确定的进度栏。
请注意,在执行长任务时,您仍然可以增加计数器。还要注意,您可以使用该程序启动多个长期运行的任务。如果那不是您想要的,您将需要对UI控件进行一些调整。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)