服务完成任务后关闭窗口(阶段)(JavaFx)

mwngjboj  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(127)

我从控制器打开了一个带有progressIndicator的窗口,因为我需要启动一个长任务。该窗口由FXML加载器生成,代码如下:

[...]
public void showProgressBar() throws IOException{
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("progress-view.fxml"));
    Scene scene = new Scene(fxmlLoader.load());
    Stage stage = new Stage();
    stage.setTitle("Caricamento");
    stage.setScene(scene);
    stage.show();
}
[...]

之后,我创建了一个服务,启动一个任务:
任务:

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;

public class GetTemperatureListTask extends Task<ObservableList<Temperature>> {
@Override
protected ObservableList<Temperature> call() throws Exception {
    updateProgress(0,100);
    Thread.sleep(1000);

    updateProgress(50,100);
    Thread.sleep(1000);

    updateProgress(100,100);
    Thread.sleep(500);

    ObservableList<Temperature> tempList = FXCollections.observableArrayList();
    tempList.add(new Temperature(10.0,"ciao"));
    tempList.add(new Temperature(20.0,"ciao"));

    return tempList;
          }
    }

服务:

package com.example.temperature.DataSource;

import com.example.temperature.domain.Temperature;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

public class GetTemperatureListService extends Service<ObservableList<Temperature>> {
@Override
protected Task<ObservableList<Temperature>> createTask() {
    return new GetTemperatureListTask();
   }
}

从Controller中,我用任务调用了服务,并将它们与progresIndicator绑定:

package com.example.temperature.controller;

import com.example.temperature.DataSource.GetTemperatureListService;
import javafx.fxml.FXML;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.AnchorPane;

public class ProgressController {
@FXML
private AnchorPane apPane;
@FXML
private ProgressIndicator piProgress;
public void initialize() {
    createProgress();
}
@FXML
public void createProgress(){
    GetTemperatureListService service = new GetTemperatureListService();
    piProgress.progressProperty().bind(service.progressProperty());
    service.start();

    
    }
   }

完成任务后如何关闭风机?

9ceoxa92

9ceoxa921#

向progressIndicator添加一个侦听器,并在lambda函数中关闭窗格获取的窗口

package com.example.temperature.controller;

import com.example.temperature.DataSource.GetTemperatureListService;
import javafx.fxml.FXML;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.AnchorPane;

public class ProgressController {
@FXML
private AnchorPane apPane;
@FXML
private ProgressIndicator piProgress;
public void initialize() {
    createProgress();
}
@FXML
public void createProgress(){
    GetTemperatureListService service = new GetTemperatureListService();
    piProgress.progressProperty().bind(service.progressProperty());
    service.start();

    service.setOnSucceeded((event)->{
        piProgress.getScene().getWindow().hide();
    });
}

相关问题