Reputation: 28576
I have a lot of code that repeats lines as below. How to make this as method ?
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
....
}
});
Upvotes: 0
Views: 898
Reputation: 468
You can also create a single instance of your drawing routines, when no arguments are required:
final Runnable tableDrawer = new Runnable()
{
@Override
public void run()
{
/* Update your TableViewer here */
}
};
then in the code, just use:
Display.getDefault().asyncExec(tableDrawer);
A few ways to optimize: If you're already in the displaythread, you can call the run method yourself--otherwise, run it asyncExec.
You can create a helper class to run these types of tasks. The helper class can check for whether you're in or out of the display thread, keep track of the number of times a drawing routine is used, and alert you when a drawing task takes too long to execute. (Anything more than 1000 milliseconds is probably not a good thing, and should be wrapped in a progress dialog.)
If you're doing a lot of GUI updates, group them so you do as many as possible in a single drawing "runnable" event. For instance, if you're drawing lines of text to a console, don't draw a single line for each line of text, instead have an ArrayList of lines that need to be drawn.. then trigger a draw when the list.size()==1. When there is a lot of lines of text to display, the speedup will be dramatic.
Upvotes: 0
Reputation: 36894
Ok, to make this more prominent, let me post an answer:
The code you have there is as short as it gets, because the only things you can pass to methods are variables or scalars.
For the special case where all your calls to Display#asyncExec(Runnable)
are the same, you could do something like this:
public class MyClass implements Runnable
{
public void myMethod()
{
/* Your other code here */
Display.getDefault().asyncExec(this);
}
@Override
public void run()
{
/* Update the GUI here */
}
}
Another alternative would be to create classes for each GUI update purpose, each implementing Runnable
:
public class GuiUpdaters
{
public static class TableViewerUpdater implements Runnable
{
@Override
public void run()
{
/* Update your TableViewer here */
}
}
public static class StatusBarUpdater implements Runnable
{
@Override
public void run()
{
/* Update your Status bar here */
}
}
}
You would call them like this:
/* Update the TableViewer */
Display.getDefault().asyncExec(new TableViewerUpdater());
/* Update the status bar */
Display.getDefault().asyncExec(new StatusBarUpdater());
Upvotes: 1