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

5.4 Event Filters - SWT: The Standard Widget Toolkit

Previous Section  < Day Day Up >  Next Section

5.4 Event Filters

An event filter is in essence a global untyped listener. Filtering an event is equivalent to adding a listener to every widget on a display. Filters run before the other event listeners, giving a filter the opportunity to modify the event or even stop the other listeners from running. To add a filter, use the following Display method.

addFilter(int eventType, Listener listener) Adds the listener to the collection of listeners that will be notified before any event of the given type is sent to any widget.

The following code fragment throws away every key as it is typed and prevents all SWT.KeyDown listeners from running.[3]

[3] This would have the effect of making all widgets unresponsive to the keyboard.






display.addFilter(SWT.KeyDown, new Listener() {

    public void handleEvent(Event event) {

        event.type = SWT.None;

        event.doit = false;

    }

});


Setting the event type field to SWT.None cancels the event. Other listeners are stopped from running because they can no longer see the event; the event is no longer a key down, and processing is halted. Setting the doit field to false for a key event consumes the event and stops the native widget from processing it. It is important to note that the doit field is consulted only for a subset of the events (including SWT.KeyDown).

Filtering on an event type allows you to intercept every event of that type as it occurs and process the event before any listeners run. In the case of the SWT.KeyDown, we were able to set doit to false and consume the event before any listener had a chance to see it.

In the same manner as listeners, event filters run in the order they were added. If a filter that was added earlier cancels the event, filters that were added later will not see the event.

To remove a filter, use the following.

removeFilter(int eventType, Listener listener) Removes the listener from the collection of listeners that will be notified before any event of the given type is sent to any widget. Note that listener must be the same instance that was passed to addFilter() in order to be successfully removed.

Filters Are Powerful and Dangerous

Event filters are generally very expensive and should be used sparingly. For example, putting a time-consuming calculation in an SWT.KeyDown filter will slow down typing for every keystroke in every widget.


    Previous Section  < Day Day Up >  Next Section