站内搜索: 请输入搜索关键词
当前页面: 图书首页 > SWT: The Standard Widget Toolkit

5.5 Runnable "Execs" - SWT: The Standard Widget Toolkit

Previous Section  < Day Day Up >  Next Section

5.5 Runnable "Execs"

In the same manner as listeners, runnable execs (referred to from now on simply as runnables) are application-defined blocks of code that are executed by the Display. However, there are several notable differences between listeners and runnables. Runnables are executed once, whereas listeners are typically invoked repeatedly, each time the event occurs. Runnables take no parameters and generally once they are added, they cannot be removed.

Runnables are used for timers (see the section Timers), executing code in the user interface thread (see the section Apartment Threading) and running code when a display is disposed.

5.5.1 Dispose Exec

The following method in class Display can be used to add a runnable that is executed when the display is disposed of.

disposeExec(Runnable runnable) Adds the runnable to the collection of Runnables that will be executed when the display is being disposed of. The runnable is executed after all widgets on the display have already been disposed of.

Notice that an important difference between disposeExec(Runnable) and the handling of the SWT.Dispose event is that dispose listeners run before any widgets have been disposed, whereas disposeExec() runnables run afterward. This means that disposeExec() can be used to free global resources, such as fonts that may be shared by many different widgets. For example, this code fragment adds a dispose runnable that releases the font used by the application after all the widgets have been disposed.






display.disposeExec(new Runnable() {

    public void run() {

        // dispose the shared font

        textFont.dispose();

    }

});


In this case, if you attempted to dispose of the font before the widgets that were using it were disposed of, exceptions would be generated. By putting it in a disposeExec() runnable, you are guaranteed that no widgets remain when the runnable is executed.

    Previous Section  < Day Day Up >  Next Section