我想在按钮被按下后显示一个标签,但在按钮所做的操作完成后,我想隐藏标签。
这就是我想做的
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和它的setOnSucceeded()来更新标签的可见性。
使用服务代替任务,因为我们需要定义一个可重用的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()
上使用侦听器,如果您想隐藏标签,无论任务成功还是失败