2016-08-02 3 views

答えて

1

コードがなくても、私は推測することができます。追加されたコードでさえ、実装からすべてのものを知るには不十分です。

このソリューションでは、実行中のタスクがあり、進行状況をプログレスバーで表示していることを前提としています。ここのタスクはサービスにラップされており、再起動することができます(おそらくこれも必要です)。

import javafx.application.Application; 
import javafx.beans.binding.Bindings; 
import javafx.concurrent.Service; 
import javafx.concurrent.Task; 
import javafx.concurrent.Worker; 
import javafx.event.ActionEvent; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.ProgressBar; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

public class CancelButtonDemo extends Application { 

    Service<Integer> service = new MyService(); 

    @Override 
    public void start(Stage primaryStage) { 

     Button start = new Button(); 
     Button cancel = new Button(); 
     ProgressBar progress = new ProgressBar(0); 

     start.setText("Run Task"); 
     start.setOnAction((ActionEvent event) -> { 
      if (!(service.getState().equals(Worker.State.READY))) { 
       service.reset(); 
      } 
      progress.progressProperty().bind(service.progressProperty()); 
      service.start(); 
     }); 
     start.disableProperty().bind(service.runningProperty()); 

     cancel.setText("Cancel Task"); 
     cancel.setOnAction((ActionEvent event) -> { 
      service.cancel(); 
      progress.progressProperty().unbind(); 
      progress.setProgress(0); 
     }); 
     cancel.disableProperty().bind(Bindings.not(service.runningProperty())); 

     VBox root = new VBox(20); 
     root.setAlignment(Pos.CENTER); 
     root.getChildren().addAll(start, progress, cancel); 
     Scene scene = new Scene(root, 300, 250); 
     primaryStage.setTitle("Cancel Button Demo"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     launch(args); 
    } 

    class MyService extends Service<Integer> { 

     @Override 
     protected Task<Integer> createTask() { 
      return new Task<Integer>() { 

       @Override 
       protected Integer call() throws Exception { 
        int iterations; 
        for (iterations = 0; iterations < 10000000; iterations++) { 
         if (isCancelled()) { 
          updateMessage("Cancelled"); 
          break; 
         } 
         updateMessage("Iteration " + iterations); 
         updateProgress(iterations, 10000000); 
        } 
        return iterations; 
       } 
      }; 
     } 
    } 
} 

上記のアプリケーションは、次のようになります。私は私の答えをudpatedまし

enter image description here

+0

私は唯一のタスクが完了すると、[キャンセル]ボタンを無効にしたい... –

+0

。 – NwDev

+0

あなたはこれらのボタンを作っています。しかし、私のキャンセルボタンはデフォルトであります。それを無効にするのはちょっと難しいです。 –

関連する問題