Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javafx.scene.Scene;
- import javafx.stage.Stage;
- import javafx.geometry.Pos;
- import javafx.scene.layout.*;
- import javafx.concurrent.Task;
- import javafx.geometry.Insets;
- import javafx.scene.CacheHint;
- import javafx.concurrent.Worker;
- import javafx.beans.binding.When;
- import javafx.concurrent.Service;
- import javafx.scene.control.Label;
- import javafx.application.Platform;
- import javafx.scene.control.Button;
- import javafx.beans.binding.Bindings;
- import javafx.scene.control.TextArea;
- import javafx.application.Application;
- import javafx.collections.FXCollections;
- import javafx.scene.control.ProgressBar;
- import javafx.collections.ObservableList;
- import static javafx.concurrent.Worker.State.RUNNING;
- import static javafx.concurrent.Worker.State.SCHEDULED;
- /**
- *
- * @author Aamir Khan
- * @Web http://aamir.io
- */
- public class OneShortTask extends Application {
- // Buttons
- Button startBtn = new Button("Start");
- Button cancelledBtn = new Button("Cancel");
- Button resetBtn = new Button("Reset");
- Button exitBtn = new Button("Exit");
- // Create the task
- Service<ObservableList<Long>> task = new Service<ObservableList<Long>>() {
- @Override
- protected Task<ObservableList<Long>> createTask() {
- return new PrimeFinder();
- // return new PrimeFinder(500, 1000);
- // return new PrimeFinder(upperLimit);
- }
- };
- /**
- * Check if the Task Was Started Before
- */
- boolean wasTaskStartedBefore = false;
- @Override
- public void start(Stage window) {
- //Event Handling
- startBtn.setOnAction(e -> startTask());
- resetBtn.setOnAction(e -> task.reset());
- cancelledBtn.setOnAction(e -> task.cancel());
- exitBtn.setOnAction(e -> Platform.exit());
- //Enable or Disable Buttons
- cancelledBtn.disableProperty().bind(task.stateProperty().isNotEqualTo(RUNNING));
- resetBtn.disableProperty().bind(Bindings.or(task.stateProperty().isEqualTo(RUNNING), task.stateProperty().isEqualTo(SCHEDULED)));
- //Creating the UI
- GridPane pane = new UI(task);
- HBox buttonBox = new HBox(5, startBtn, resetBtn, cancelledBtn, exitBtn);
- buttonBox.setPadding(new Insets(5, 0, 0, 0));
- buttonBox.setAlignment(Pos.BOTTOM_RIGHT);
- BorderPane root = new BorderPane();
- root.setCenter(pane);
- root.setBottom(buttonBox);
- root.setStyle("-fx-padding: 10;"
- + "-fx-border-style: solid inside;"
- + "-fx-border-width: 2;"
- + "-fx-border-insets: 5;"
- + "-fx-border-radius: 5;"
- + "-fx-border-color: blue;");
- Scene scene = new Scene(root);
- window.setScene(scene);
- window.setTitle("A Prime Number Finder Task");
- window.show();
- }
- /**
- * Start the Task
- */
- public void startTask() {
- if (wasTaskStartedBefore) {
- task.restart();
- } else {
- task.start();
- wasTaskStartedBefore = true;
- startBtn.setText("Restart");
- }
- }
- /**
- * Mr. Main the Entry PoinT
- *
- * @param args
- */
- public static void main(String[] args) {
- launch(args);
- }
- /******************************************************
- * *
- * The Task implementation *
- * *
- *******************************************************/
- class PrimeFinder extends Task<ObservableList<Long>> {
- private long lowerLimit = 1L;
- private long upperLimit = 100L;
- private final long sleepTime = 500;
- /**
- * Default Constructor
- */
- public PrimeFinder() {
- }
- /**
- * Initializes the <code>upperLimit</code> with the Given Value..
- */
- public PrimeFinder(long upperLimit) {
- this.upperLimit = upperLimit;
- }
- /**
- * Initializes Both <code>lowerLimit</code> and <code>upperLimit</code>
- * with the Given Values..
- */
- public PrimeFinder(long lowerLimit, long upperLimit) {
- this.lowerLimit = lowerLimit;
- this.upperLimit = upperLimit;
- }
- @Override
- protected ObservableList<Long> call() {
- // An observable list to represent the result
- final ObservableList<Long> result = FXCollections.<Long>observableArrayList();
- // Update the title
- this.updateTitle("Prime Number Finder Task");
- long count = this.upperLimit - this.lowerLimit + 1;
- long counter = 0;
- // Process numbers
- for (long i = lowerLimit; i <= upperLimit; i++) {
- // Check if the task is cancelled
- if (this.isCancelled()) {
- break;
- }
- // Increment the counter
- counter++;
- // Update message
- this.updateMessage("Checking " + i + " for a prime number");
- // Sleep for some time
- try {
- Thread.currentThread().sleep(this.sleepTime);
- } catch (InterruptedException e) {
- // Check if the task is cancelled While Thread was Sleeping
- if (this.isCancelled()) {
- break;
- }
- }
- // Check if the number is a prime number
- if (isPrime(i)) {
- // if Yes, Add it to the list
- result.add(i);
- // Also Publish the read-only list
- // partial results
- updateValue(FXCollections.<Long>unmodifiableObservableList(result));
- }
- // Update the progress/bar
- updateProgress(counter, count);
- }
- return result;
- }
- @Override
- protected void cancelled() {
- super.cancelled();
- updateMessage("The task was cancelled.");
- }
- @Override
- protected void failed() {
- super.failed();
- updateMessage("The task failed.");
- }
- @Override
- public void succeeded() {
- super.succeeded();
- updateMessage("The task finished successfully.");
- }
- /**
- * Checks the Given Number is Prime or NOt
- * @param num Number to be Check
- * @return true if the Given Number is Prime, else false
- */
- public boolean isPrime(long num) {
- if (num <= 1 || num % 2 == 0) {
- return false;
- }
- int upperDivisor = (int) Math.ceil(Math.sqrt(num));
- for (int divisor = 3; divisor <= upperDivisor; divisor += 2) {
- if (num % divisor == 0) {
- return false;
- }
- }
- return true;
- }
- }//PrimeFinder Ends
- /******************************************************
- * *
- * UI Stuff *
- * *
- *******************************************************/
- class UI extends GridPane {
- private final Label title = new Label("");
- private final Label message = new Label("");
- private final Label running = new Label("");
- private final Label state = new Label("");
- private final Label totalWork = new Label("");
- private final Label workDone = new Label("");
- private final Label progress = new Label("");
- private final TextArea value = new TextArea("");
- private final TextArea exception = new TextArea("");
- private final ProgressBar progressBar = new ProgressBar();
- public UI(Worker<ObservableList<Long>> worker) {
- addUI();
- bindToWorker(worker);
- }
- private void addUI() {
- value.setPrefColumnCount(20);
- value.setPrefRowCount(3);
- exception.setPrefColumnCount(20);
- exception.setPrefRowCount(3);
- progressBar.setCache(true);
- progressBar.setCacheHint(CacheHint.SPEED);
- this.setHgap(5);
- this.setVgap(5);
- addRow(0, new Label("Title:"), title);
- addRow(1, new Label("Message:"), message);
- addRow(2, new Label("Running:"), running);
- addRow(3, new Label("State:"), state);
- addRow(4, new Label("Total Work:"), totalWork);
- addRow(5, new Label("Work Done:"), workDone);
- addRow(6, new Label("Progress:"), new HBox(2, progressBar, progress));
- addRow(7, new Label("Value:"), value);
- addRow(8, new Label("Exception:"), exception);
- }
- /**
- * Bind Labels to the properties of the worker
- */
- public final void bindToWorker(final Worker<ObservableList<Long>> worker) {
- title.textProperty().bind(worker.titleProperty());
- message.textProperty().bind(worker.messageProperty());
- running.textProperty().bind(new When(worker.runningProperty()).then("Yes").otherwise("No"));
- state.textProperty().bind(worker.stateProperty().asString());
- totalWork.textProperty().bind(new When(worker.totalWorkProperty().isEqualTo(-1))
- .then("Unknown")
- .otherwise(worker.totalWorkProperty().asString()));
- workDone.textProperty().bind(new When(worker.workDoneProperty().isEqualTo(-1))
- .then("Unknown")
- .otherwise(worker.workDoneProperty().asString()));
- progress.textProperty().bind(new When(worker.progressProperty().isEqualTo(-1))
- .then("0%")
- .otherwise(worker.progressProperty().multiply(100.0)
- .asString("%.0f%%")));
- progressBar.progressProperty().bind(worker.progressProperty());
- value.textProperty().bind(worker.valueProperty().asString());
- // if any Exception occurs
- worker.exceptionProperty().addListener((ov, oldValue, newValue) -> {
- if (newValue != null) {
- exception.setText(newValue.getLocalizedMessage());
- newValue.printStackTrace();
- } else {
- exception.setText("");
- }
- });
- }
- }//UI Ends
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement