简体   繁体   English

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

[英]JavaFX - How to pause a background Service with UI controller event?

With JavaFX UI controller event I want to pause the background Service, service which start with that UI controller (as show on following code). 对于JavaFX UI控制器事件,我想暂停后台服务,该服务以该UI控制器开头(如以下代码所示)。

I have found a similar post JavaFX2: Can I pause a background Task / Service . 我发现了类似的文章JavaFX2:我可以暂停后台任务/服务 But with that post it will give solution to pause a Service with it's own events, not for events fire with external UI Controller. 但是,在发布该帖子时,它将提供解决方案来暂停具有自身事件的服务,而不是针对使用外部UI Controller触发的事件。

Actually in this case it seems I have to set the Service's internal State to make it pause but Worker Interface didn't contains such a Sate. 实际上,在这种情况下,似乎必须设置服务的内部状态以使其暂停,但辅助接口不包含这样的状态。 As a example we can force to fail a Service, with it's FAILED State etc. 例如,我们可以通过服务的失败状态等强制服务失败。

Thanks. 谢谢。

UI Controller class UI Controller类

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") {

   }
 }

}

Service class 服务等级

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;            
        }
    }
  }    
}

Hej Channa, Hej Channa,

here is an example how you can "pause" your Service and after closing the Dialog resume it. 这是一个示例,您可以如何“暂停” Service并在关闭Dialog恢复它。

Here is the FXML ;) 这是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);
    }

}

The Controller 控制器

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();
        }


    }
}

And the MyService class 还有MyService类

I run a for Loop on the Console and print out the Numbers. 我在控制台上运行for循环并打印出数字。 If i call the pause() Method of MyService i cancel() it and restart() it on the call of resume() Method. 如果我调用MyServicepause()方法,我会cancel()并在调用resume()方法时restart() The Thread.sleep(2000L); Thread.sleep(2000L); i only added to simulate a long running Task . 我只是添加了模拟长时间运行的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();
    }
}

Patrick 帕特里克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM