任务完成后如何在javafx中显示然后隐藏标签

How to show and then hide a label in javafx after a task is completed

我想在按下按钮后显示标签,但在按钮的操作完成后我想隐藏标签。

这是我尝试过的

    final Label loadingLabel = new Label();
    loadingLabel.setText("Loading...");
    loadingLabel.setFont(Font.font("Arial", 16));

    BorderPane root = new BorderPane();
    root.setRight(label);
    root.setLeft(button);
    root.setCenter(loadingLabel);
    loadingLabel.setVisible(false);

final Button printButton = new Button("Print part");
    printButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            loadingLabel.setVisible(true);
            //here are some computations
            loadingLabel.setVisible(false);
        }
    }

代码根本没有显示标签。

这是一个简单的示例,说明如何使用 Service and its setOnSucceeded() 更新标签的可见性。

使用 service 而不是 Task 因为我们需要定义一个可重用的 Worker 对象。

import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SimpleTaskExample extends Application {

    Service service = new ProcessService();

    @Override
    public void start(Stage primaryStage) throws Exception {
        Button button = new Button("Press Me to start new Thread");

        Label taskLabel = new Label("Task Running..");
        taskLabel.setVisible(false);
        Label finishLabel = new Label("Task Completed.");
        finishLabel.setVisible(false);

        VBox box = new VBox(20, taskLabel, button, finishLabel);
        box.setAlignment(Pos.CENTER);
        primaryStage.setScene(new Scene(box, 200, 200));
        primaryStage.show();

        button.setOnAction(event -> {

            // show the label
            taskLabel.setVisible(true);
            // hide finish label
            finishLabel.setVisible(false);
            // start background computation
            if(!service.isRunning())
                service.start();
        });

        // If task completed successfully, hide the label
        service.setOnSucceeded(e -> {
            taskLabel.setVisible(false);
            finishLabel.setVisible(true);
            //reset service
            service.reset();
        });
    }

    class ProcessService extends Service<Void> {

        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    // Computations takes 3 seconds
                    // Calling Thread.sleep instead of random computation
                    Thread.sleep(3000);
                    return null;
                }
            };
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

你也可以在服务的 runningProperty() 上使用监听器,如果你想隐藏标签而不管任务是成功还是失败。