Reputation: 749
In my SWT GUI, I would like to have a button that kicks off a job and while running that job, update a textbox that will show a log of the events of that job. However, my textbox does not update until the end of my asyncExec() call. In the example below, I would like for my textbox to be updated every second, but instead it gets all of the updates at once after 10 full seconds when it finishes executing.
Is there a way to achieve this?
private void UpdateUI()
{
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run()
{
StringBuilder sb = new StringBuilder();
for(int i=1; i<=10; i++)
{
sb.append("Running iteration " + i + "\n");
txtLogBox.setText(sb.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}});
}
Upvotes: 1
Views: 1363
Reputation: 78673
You're sleeping in the UI thread. You need to do your long-running work in a different thread and only post updates to the UI thread using asyncExec
. For example:
new Thread(new Runnable() {
public void run()
{
StringBuilder sb = new StringBuilder();
for(int i=1; i<=10; i++)
{
sb.append("Running iteration " + i + "\n");
final String result = sb.toString();
Display.getDisplay().asyncExec(new Runnable() {
public void run()
{
txtLogBox.setText(result);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Upvotes: 2