Reputation: 117
I have a case where I need to update a gui component based on operations performed in another thread. For this I have the following:
A class that extends WebPage and creates an input field, a form and a label. When the form is submitted a thread that processes data from the input file is started and an AbstractAjaxTimerBehavior is attached to the page which updates the label with the progress/status of the thread.
Because I cannot access the thread object in the onTimer () method of the ajax timer, I pass on a reference of the class to the thread upon it's creation. The thread then updates a variable (status) of the class with it's progress. What the ajax timer does is it updates the label's value with the status value.
public int status;
@Override
public void onSubmit ()
{
final Task task = new Task (ViewPage.this);
Thread thread = new Thread (task);
thread.start ();
AbstractAjaxTimerBehavior timer = new AbstractAjaxTimerBehavior (Duration.milliseconds (1000))
{
private static final long serialVersionUID = 1L;
@Override
protected void onTimer (AjaxRequestTarget target)
{
System.out.println ("> Progress [" + status + "]");
if (status == x)
{
// refresh page
setResponsePage (getPage().getClass ());
}
}
};
getPage().add (timer);
}
Is there a way that I can update the label's value by accessing the thread object directly from the ajax timer or in a clean way?
Upvotes: 0
Views: 2107
Reputation: 117
I found a good answer here: Wicket countdown timer will not self-update
I created a model class that has status member. Then create an instance of this class and set it as Label's model and also pass it to the thread to update the status value. Then in the onTimer () method add the label to be updated.
public class ProgressModel implements IModel<String>
{
private static final long serialVersionUID = 1L;
public String status;
@Override
public void detach ()
{
// TODO Auto-generated method stub
}
@Override
public String getObject ()
{
return status;
}
@Override
public void setObject (String object)
{
status = object;
}
}
Create model instance and set it to the Label object
pm = new ProgressModel ();
statusLbl = new Label ("statusLbl", pm);
statusLbl.setOutputMarkupId (true);
In the onTimer () method of the AbstractAjaxTimerBehavior just set the Label object to be updated
@Override
protected void onTimer (AjaxRequestTarget target)
{
target.add (statusLbl);
}
In the thread class I have:
class Task implements Runnable
{
public Task (ProgressModel progressModel)
{
this.pm = progressModel;
}
@Override
public void run ()
{
// some operations
pm.status = x;
}
}
Upvotes: 1
Reputation: 3860
You could use:
http://wicket.apache.org/apidocs/1.4/org/apache/wicket/ajax/AjaxSelfUpdatingTimerBehavior.html
I think you can attach this to any component to re-render after a certain time:
component.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)));
This will simply rerender and you can access your ressources and update the label.
Sebastian
Upvotes: 1