Reputation: 564
I am trying to update a ProgressBar
that is added to a separate Stage in javafx
. I have defined task in a method named messagemerge()
and a new thread containing this task is called from there. Each time i try to use the task that is returned by the method messagemerge()
to the main, it throws a NullPointerException
This is what i have tried
ProgressBarDialog progressBarDialog=new ProgressBarDialog();
Task<Void> task=messageMerge();
progressBarDialog.progressBar.progressProperty().bind(task.progressProperty());
The above code is written in the main
The method messageMerge()
is as defined below
public Task<Void> messageMerge() throws Exception
{
task=new Task<Void>(){
protected Void call()throws Exception{
for(i=0;i<50;i++)
updateProgress(i,50);
}
return null;
};
Thread thread=new Thread(task);
thread.start();
return task;
}
The progessBarDialog
is another class defined as below
public class ProgressBarDialog {
public ProgressBar progressBar=null;
public ProgressBarDialog()
{
Stage progressDialog=new Stage();
progressDialog.initModality(Modality.APPLICATION_MODAL);
ProgressBar progressBar=new ProgressBar();
progressBar.setProgress(0);
BorderPane progressPane=new BorderPane();
progressPane.setCenter(progressBar);
progressDialog.setScene(new Scene(progressPane,500,100));
progressDialog.show();
}
NullPointerException
occurs when i try to access task.progressProperty()
from the main. Could someone please help me on this. Any help is appreciated.
Upvotes: 0
Views: 707
Reputation: 159291
What is Wrong
It is just a logic error, you aren't initializing the progressBar member variable and it is always null. When you try to use the progressBar member, you get a NullPointerException.
Essentially, you are "shadowing" the progressBar variable by redeclaring it in a different scope, so your original variable is never assigned a value.
How to Fix
To fix this issue, replace the following line:
ProgressBar progressBar=new ProgressBar()
with:
progressBar=new ProgressBar()
Not related, but suspicious code in your sample
Incidentally, the task usage in your messageMerge function also looks suspicious, you should probably be declaring the task locally to your method (though that is unlikely to be the source of your NullPointerException). massageMerge is returning a task, so you usually don't need to set a class member variable to the same value from within the function (because your invoking code can just use the value returned from the massageMerge function).
Instead of:
task=new Task<Void>() { ...
You probably want:
Task<Void> task=new Task<>() { ...
Alternate implementations
You don't need to code a ProgressDialog yourself, you can use the Makery progress dialog example based on only the JavaFX APIs, or you can use the third party ControlsFX ProgressDialog.
Take care to set window ownership correctly for Modality
Either way, you probably want to pay attention to Window Modality.
Upvotes: 3