How to show and then hide a shortcut in javafx after a task completes
I want to show the label after the button is clicked, but after completing the operations done by the button, I want the label to be hidden.
This is what I tried to do
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);
}
}
The code doesn't appear on the label at all.
+3
source to share
1 answer
Here's a simple example of how you can use Service and setOnSucceeded () to update the visibility of labels.
A service is used instead of Task because we need to define a reusable object.
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);
}
}
You can also use a listener in runningProperty()
services if you want to hide the shortcut regardless of whether a task is running or not running.
+3
source to share