Saturday, 29 June 2013

How to Create Progress Indicator in JavaFX

Hi,

  Wondering how to use Progress Indicator in JavaFX

    like to have a progress bar which shows the progress of program/task completed ?

    Well, thats quite simple using JavaFX!!

    First thing we need to create a JavaFX FXML project,If you dont know follow this post.
  
    Once the project is created first step is to design the User Interface, for this demo i have created
    like this

createworker(), dynamic UI, FXML, javaFX, progress bar in javafx, Progress Indicator in javafx, progress property, task in javafx, user interface in javafx,


   Replace your code in .fxml file with this one

<?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.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxprogressindicator.SampleController">

  <children>
    <Button fx:id="start" layoutX="26.0" layoutY="14.0" onAction="#handleButtonAction"
      text="Start" />

    <Label fx:id="label" layoutX="55.0" layoutY="73.0" minHeight="16.0" minWidth="69.0" />

    <ProgressIndicator fx:id="progress" layoutX="83.0" layoutY="113.0" prefHeight="62.0"
      prefWidth="138.0" progress="0.0" />

    <Button fx:id="stop" layoutX="200.0" disable="true"  layoutY="14.0" onAction="#stopAction"
      mnemonicParsing="false" text="cancel" />
  </children>

</AnchorPane>

This creates a Anchor pane and adds

2 Buttons start and cancel
1 Progress Indicator refered as progress
1 Label just to inform you that your program has started.

Now your done with UI creation next is creating event handler for it.

Creating event handler? where did we registered our event?

I know you got these question check above code when we created a button we used onAction="#eventname"

This attribute specifies the eventhandler to be called when a action is performed on it.

Now creating the event handlers

@FXML
    private void handleButtonAction()
 {
      // this will be executed when button is clicked, if you have registered this handler as above
 }

Now for this demo

Paste the following code in your controller file for using progress indicator

//Two button handlers for stop and start respectively

 @FXML
    private void stopAction()
    {
       //when cancel button is clicked it will end the task created and
        worker.cancel(true);
      //unbinds progress indicator from that task
         progress.progressProperty().unbind();
     //set it to 0
         progress.setProgress(0);
        start.setDisable(false);
    }
    @FXML
    private void handleButtonAction() {
        //setDisable() is used to enable or disable the elements
        stop.setDisable(false);
        start.setDisable(true);
        label.setText("Now your program is progressing!!");
        progress.progressProperty().unbind();
        progress.setProgress(0);
      //creating a new task
        worker = createWorker();
        //binding it with that task
        progress.progressProperty().bind(worker.progressProperty());
         //you can pass any value while task is executing and it can printed on console or set to label
                worker.messageProperty().addListener(new ChangeListener<String>() {
                    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                        System.out.println(newValue);
                    }
                });
                // task started on new thread
                 new Thread(worker).start();
               
    }
    public Task createWorker() {
        return new Task() {
            // call() should be overridden

            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(2000);
                  //updateMessage() is used to pass the values to be printed on screen or console
                    updateMessage("2000 milliseconds");
                  //this is used to show the progress
                    updateProgress(i + 1, 10);
                }
                 worker.cancel(true);
                return true;
            }
        };
    }

OMG!! what is this code, if you dint understood anything dont worry I will explain about Task in my next post

For now Task is used to do some work in background and  which may change our UserInterface dynamically (while running the programm) its similar to Threads , but using threads we can't change the UI when running the program.

Check comments for above code explaination and what ever you want to perform in background do it
 in createworker() .

Thats all you can run your program and you will see progress indicator showing the progress of
your program.


your final output will be this

createworker(), dynamic UI, FXML, javaFX, progress bar in javafx, Progress Indicator in javafx, progress property, task in javafx, user interface in javafx,

Download the complete source code from here

Please feel free to leave your comments or doubts

thank you :)

No comments:

Post a Comment