Advertisement
iamaamir

Multi tasking in javafx

Mar 12th, 2016
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.91 KB | None | 0 0
  1. import javafx.scene.Scene;
  2. import javafx.stage.Stage;
  3. import javafx.geometry.Pos;
  4. import javafx.scene.layout.*;
  5. import javafx.concurrent.Task;
  6. import javafx.geometry.Insets;
  7. import javafx.scene.CacheHint;
  8. import javafx.concurrent.Worker;
  9. import javafx.beans.binding.When;
  10. import javafx.concurrent.Service;
  11. import javafx.scene.control.Label;
  12. import javafx.application.Platform;
  13. import javafx.scene.control.Button;
  14. import javafx.beans.binding.Bindings;
  15. import javafx.scene.control.TextArea;
  16. import javafx.application.Application;
  17. import javafx.collections.FXCollections;
  18. import javafx.scene.control.ProgressBar;
  19. import javafx.collections.ObservableList;
  20. import static javafx.concurrent.Worker.State.RUNNING;
  21. import static javafx.concurrent.Worker.State.SCHEDULED;
  22.  
  23. /**
  24.  *
  25.  * @author  Aamir Khan
  26.  * @Web http://aamir.io
  27.  */
  28. public class OneShortTask extends Application {
  29.  
  30. //    Buttons
  31.     Button startBtn = new Button("Start");
  32.     Button cancelledBtn = new Button("Cancel");
  33.     Button resetBtn = new Button("Reset");
  34.     Button exitBtn = new Button("Exit");
  35.  
  36.     // Create the task
  37.     Service<ObservableList<Long>> task = new Service<ObservableList<Long>>() {
  38.  
  39.         @Override
  40.         protected Task<ObservableList<Long>> createTask() {
  41.             return new PrimeFinder();
  42. //            return new PrimeFinder(500, 1000);
  43. //            return new PrimeFinder(upperLimit);
  44.         }
  45.  
  46.     };
  47.  
  48.     /**
  49.      * Check if the Task Was Started Before
  50.      */
  51.     boolean wasTaskStartedBefore = false;
  52.  
  53.     @Override
  54.     public void start(Stage window) {
  55.         //Event Handling
  56.         startBtn.setOnAction(e -> startTask());
  57.         resetBtn.setOnAction(e -> task.reset());
  58.         cancelledBtn.setOnAction(e -> task.cancel());
  59.         exitBtn.setOnAction(e -> Platform.exit());
  60.  
  61.         //Enable or Disable Buttons
  62.         cancelledBtn.disableProperty().bind(task.stateProperty().isNotEqualTo(RUNNING));
  63.         resetBtn.disableProperty().bind(Bindings.or(task.stateProperty().isEqualTo(RUNNING), task.stateProperty().isEqualTo(SCHEDULED)));
  64.  
  65.         //Creating the UI
  66.         GridPane pane = new UI(task);
  67.  
  68.         HBox buttonBox = new HBox(5, startBtn, resetBtn, cancelledBtn, exitBtn);
  69.         buttonBox.setPadding(new Insets(5, 0, 0, 0));
  70.         buttonBox.setAlignment(Pos.BOTTOM_RIGHT);
  71.  
  72.         BorderPane root = new BorderPane();
  73.         root.setCenter(pane);
  74.         root.setBottom(buttonBox);
  75.         root.setStyle("-fx-padding: 10;"
  76.                 + "-fx-border-style: solid inside;"
  77.                 + "-fx-border-width: 2;"
  78.                 + "-fx-border-insets: 5;"
  79.                 + "-fx-border-radius: 5;"
  80.                 + "-fx-border-color: blue;");
  81.  
  82.         Scene scene = new Scene(root);
  83.  
  84.         window.setScene(scene);
  85.         window.setTitle("A Prime Number Finder Task");
  86.         window.show();
  87.     }
  88.  
  89.     /**
  90.      * Start the Task
  91.      */
  92.     public void startTask() {
  93.         if (wasTaskStartedBefore) {
  94.             task.restart();
  95.         } else {
  96.             task.start();
  97.             wasTaskStartedBefore = true;
  98.             startBtn.setText("Restart");
  99.         }
  100.     }
  101.  
  102.     /**
  103.      * Mr. Main the Entry PoinT
  104.      *
  105.      * @param args
  106.      */
  107.     public static void main(String[] args) {
  108.  
  109.         launch(args);
  110.     }
  111.  
  112.     /******************************************************
  113.     *                                                     *
  114.     *                The Task implementation              *
  115.     *                                                     *
  116.     *******************************************************/
  117.    
  118.     class PrimeFinder extends Task<ObservableList<Long>> {
  119.  
  120.         private long lowerLimit = 1L;
  121.         private long upperLimit = 100L;
  122.         private final long sleepTime = 500;
  123.        
  124.         /**
  125.          * Default Constructor
  126.          */
  127.         public PrimeFinder() {
  128.         }
  129.  
  130.         /**
  131.          * Initializes the <code>upperLimit</code> with the Given Value..
  132.          */
  133.         public PrimeFinder(long upperLimit) {
  134.             this.upperLimit = upperLimit;
  135.         }
  136.  
  137.         /**
  138.          * Initializes Both <code>lowerLimit</code> and <code>upperLimit</code>
  139.          * with the Given Values..
  140.          */
  141.         public PrimeFinder(long lowerLimit, long upperLimit) {
  142.             this.lowerLimit = lowerLimit;
  143.             this.upperLimit = upperLimit;
  144.         }
  145.  
  146.  
  147.        
  148.         @Override
  149.         protected ObservableList<Long> call() {
  150.             // An observable list to represent the result
  151.             final ObservableList<Long> result = FXCollections.<Long>observableArrayList();
  152.             // Update the title
  153.             this.updateTitle("Prime Number Finder Task");
  154.            
  155.             long count = this.upperLimit - this.lowerLimit + 1;
  156.             long counter = 0;
  157.            
  158.             // Process numbers
  159.             for (long i = lowerLimit; i <= upperLimit; i++) {
  160.                 // Check if the task is cancelled
  161.                 if (this.isCancelled()) {
  162.                     break;
  163.                 }
  164.                 // Increment the counter
  165.                 counter++;
  166.                 // Update message
  167.                 this.updateMessage("Checking " + i + " for a prime number");
  168.                 // Sleep for some time
  169.                 try {
  170.                     Thread.currentThread().sleep(this.sleepTime);
  171.                 } catch (InterruptedException e) {
  172.                     // Check if the task is cancelled While Thread was Sleeping
  173.                     if (this.isCancelled()) {
  174.                         break;
  175.                     }
  176.                 }
  177.                 // Check if the number is a prime number
  178.                 if (isPrime(i)) {
  179.                     // if Yes, Add it to the list
  180.                     result.add(i);
  181.                     // Also Publish the read-only list
  182.                     // partial results
  183.                     updateValue(FXCollections.<Long>unmodifiableObservableList(result));
  184.                 }
  185.  
  186.                 // Update the progress/bar
  187.                 updateProgress(counter, count);
  188.             }
  189.             return result;
  190.         }
  191.  
  192.         @Override
  193.         protected void cancelled() {
  194.             super.cancelled();
  195.             updateMessage("The task was cancelled.");
  196.         }
  197.  
  198.         @Override
  199.         protected void failed() {
  200.             super.failed();
  201.             updateMessage("The task failed.");
  202.         }
  203.  
  204.         @Override
  205.         public void succeeded() {
  206.             super.succeeded();
  207.             updateMessage("The task finished successfully.");
  208.         }
  209.         /**
  210.          * Checks the Given Number is Prime or NOt
  211.          * @param num   Number to be Check
  212.          * @return true if the Given Number is Prime, else false
  213.          */
  214.         public boolean isPrime(long num) {
  215.             if (num <= 1 || num % 2 == 0) {
  216.                 return false;
  217.             }
  218.             int upperDivisor = (int) Math.ceil(Math.sqrt(num));
  219.             for (int divisor = 3; divisor <= upperDivisor; divisor += 2) {
  220.                 if (num % divisor == 0) {
  221.                     return false;
  222.                 }
  223.             }
  224.             return true;
  225.         }
  226.     }//PrimeFinder Ends
  227.    
  228.    
  229.    
  230.    
  231.  
  232.     /******************************************************
  233.     *                                                     *
  234.     *                   UI Stuff                          *
  235.     *                                                     *
  236.     *******************************************************/
  237.     class UI extends GridPane {
  238.  
  239.         private final Label title = new Label("");
  240.         private final Label message = new Label("");
  241.         private final Label running = new Label("");
  242.         private final Label state = new Label("");
  243.         private final Label totalWork = new Label("");
  244.         private final Label workDone = new Label("");
  245.         private final Label progress = new Label("");
  246.         private final TextArea value = new TextArea("");
  247.         private final TextArea exception = new TextArea("");
  248.         private final ProgressBar progressBar = new ProgressBar();
  249.  
  250.         public UI(Worker<ObservableList<Long>> worker) {
  251.             addUI();
  252.             bindToWorker(worker);
  253.         }
  254.  
  255.         private void addUI() {
  256.            
  257.             value.setPrefColumnCount(20);
  258.             value.setPrefRowCount(3);
  259.            
  260.             exception.setPrefColumnCount(20);
  261.             exception.setPrefRowCount(3);
  262.            
  263.             progressBar.setCache(true);
  264.             progressBar.setCacheHint(CacheHint.SPEED);
  265.            
  266.             this.setHgap(5);
  267.             this.setVgap(5);
  268.            
  269.             addRow(0, new Label("Title:"), title);
  270.             addRow(1, new Label("Message:"), message);
  271.             addRow(2, new Label("Running:"), running);
  272.             addRow(3, new Label("State:"), state);
  273.             addRow(4, new Label("Total Work:"), totalWork);
  274.             addRow(5, new Label("Work Done:"), workDone);
  275.             addRow(6, new Label("Progress:"), new HBox(2, progressBar, progress));
  276.             addRow(7, new Label("Value:"), value);
  277.             addRow(8, new Label("Exception:"), exception);
  278.         }
  279.         /**
  280.         * Bind Labels to the properties of the worker
  281.         */
  282.         public final void bindToWorker(final Worker<ObservableList<Long>> worker) {
  283.            
  284.             title.textProperty().bind(worker.titleProperty());
  285.             message.textProperty().bind(worker.messageProperty());
  286.             running.textProperty().bind(new When(worker.runningProperty()).then("Yes").otherwise("No"));
  287.             state.textProperty().bind(worker.stateProperty().asString());
  288.            
  289.             totalWork.textProperty().bind(new When(worker.totalWorkProperty().isEqualTo(-1))
  290.                     .then("Unknown")
  291.                     .otherwise(worker.totalWorkProperty().asString()));
  292.  
  293.             workDone.textProperty().bind(new When(worker.workDoneProperty().isEqualTo(-1))
  294.                     .then("Unknown")
  295.                     .otherwise(worker.workDoneProperty().asString()));
  296.  
  297.             progress.textProperty().bind(new When(worker.progressProperty().isEqualTo(-1))
  298.                     .then("0%")
  299.                     .otherwise(worker.progressProperty().multiply(100.0)
  300.                             .asString("%.0f%%")));
  301.            
  302.             progressBar.progressProperty().bind(worker.progressProperty());
  303.             value.textProperty().bind(worker.valueProperty().asString());
  304.            
  305.             // if any Exception occurs
  306.             worker.exceptionProperty().addListener((ov, oldValue, newValue) -> {
  307.                 if (newValue != null) {
  308.                     exception.setText(newValue.getLocalizedMessage());
  309.                    
  310.                     newValue.printStackTrace();
  311.                 } else {
  312.                     exception.setText("");
  313.                 }
  314.             });
  315.         }
  316.     }//UI Ends
  317.  
  318. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement