JavaFX - 如何使用UI控制器事件暂停后台服务?

时间:2014-07-30 02:27:20

标签: java multithreading service concurrency javafx

使用JavaFX UI控制器事件我想暂停后台服务,该服务以该UI控制器开始(如下面的代码所示)。

我找到了类似的帖子JavaFX2: Can I pause a background Task / Service。但是,通过该帖子,它将提供解决方案,使用自己的事件暂停服务,而不是使用外部UI控制器触发事件​​。

实际上在这种情况下,似乎我必须设置服务的内部状态以使其暂停,但工作者接口不包含这样的状态。作为一个例子,我们可以强制使服务失败,因为它处于FAILED状态等。

感谢。

UI控制器类

public class CommandController implements Initializable {

 private CommandService commandService;
 private ExecutorService sequentialServiceExecutor;
 private List<IOCommandService> servicePool = new ArrayList<>();

 @Override
 public void initialize(URL location, Resources resources) {

   doProceedInitialSteps(); 
 }

 private void doProceedInitialSteps() { 

   // Select available IOCommands 
   List<IOCommand> commandList = commandService.getCommands();

   // Initialised ExecutorService on sequential manner
   sequentialServiceExecutor = Executors.newFixedThreadPool(
                1,
                new ServiceThreadFactory()
   );

   for (final IOCommand command : commandList) { 

        IOCommandService service = new IOCommandService(command, this);

        service.setExecutor(sequentialServiceExecutor);

        service.setOnRunning(new EventHandler<IOCommand>() { }

        service.setOnSucceeded(new EventHandler<IOCommand>() { }

        service.setOnFailed(new EventHandler<IOCommand>() { }

        service.start();

        servicePool.add(service);       
   }

 }

 @FXML
 public void onCancel() {

   // TODO: Need to pause current executing IOCommandService until receive the user response from the DialogBox

   // Unless pause current executing IOCommandService, that will over lap this dialog box with IOCommandService related dialog boxes etc  

   Dialogs.DialogResponse response = Dialogs.showWarningDialog();

   if(response.toString.equals("OK") {

   }
 }

}

服务类

public class IOCommandService extends Service<IOCommand> {

  private IOCommand command;
  private CommandController controller;

  public IOCommandService (IOCommand command, CommandController controller) {
     this.command = command;
     this.controller = controller;
  }

  @Override
  protected Task<IOCommand> createTask() {

    return new Task<IOCommand>() {

        @Override
        protected Integer call() throws Exception {

         // Execute the IO command by,
         // 1) updating some UI components (label, images etc) on CommandController
         // 2) make enable popup some Dialog boxes for get user response  

         return command;            
        }
    }
  }    
}

1 个答案:

答案 0 :(得分:2)

Hej Channa,

这里有一个例子,你可以&#34;暂停&#34;您的Service以及关闭Dialog后恢复它。

这是FXML;)

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="de.professional_webworkx.stopservice.FXMLController">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
    </children>
</AnchorPane>

MainApplication

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        Scene scene = new Scene(root);

        stage.setTitle("JavaFX and Concurrency");
        stage.setScene(scene);
        stage.show();
    }


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

}

控制器

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class FXMLController implements Initializable {

    @FXML
    private Label label;
    private MyService ms;
    @FXML
    private void handleButtonAction(ActionEvent event) {
        onCancel();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        ms = new MyService();
        Platform.runLater(() -> {
            ms.start();
        });
    }    

    public void onCancel() {

        if(ms.getState().equals(Worker.State.RUNNING)) {
            ms.cancel();
        }
        Scene s = new Scene(new Label("Dialog"), 640, 480);
        Stage dialog = new Stage();
        dialog.setScene(s);
        dialog.showAndWait();

        if(!dialog.isShowing()) {
            ms.resume();
        }


    }
}

MyService类

我在控制台上运行for循环并打印出Numbers。如果我在调用pause()方法时调用MyService方法cancel()restart()resume()方法。 Thread.sleep(2000L);我只是添加了模拟长时间运行的Task

import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

/**
 *
 * @author Patrick Ott
 * @version 1.0
 */
public class MyService extends ScheduledService<Void> {

    Task<Void> task;
    int n = 1000000000;
    @Override
    protected Task<Void> createTask() {
        return new Task() {

            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < n; i++) {
                    System.out.println("Halllo " + n);
                    Thread.sleep(2000);
                    n--;
                }
                return null;
            }
        };
    }

    public void pause() {
        this.cancel();
    }

    public void resume() {
        System.out.println("n="+n);
        this.restart();
    }
}

帕特里克