Gui Event Wrapper

[CategoryPattern]

I'm not a pattern guru. This probably isn't even a pattern, or may have a more generic form. But I've found it useful... please edit.

Context

Java GUI event handling.

Applicability

Java programs whose GUI needs to perform the same actions for many events.

Problem

Java's GUI events are sent to directly to EventListeners? that are scattered throughout your code. There's no way to install generic code that is called before and after every EventListener?, but you want a generic exception handler or other code to wrap every event.

Forces

Solution

Create a generic EventHandler class to be called from within your EventListeners?. It's best described by example: Here, we install an UnexpectedErrorDialog?.

 public class ExampleGui? {...
   public ExampleGui?() {
     ...
     exampleButton.addActionListener(new ActionListener(ActionEvent e) {
       EventHandler.doEvent(new EventHandler() {
         public void eventBody() {
           // regular event handling code goes here
         }
       })
     });
     ...
   }
   ...
 }

public class EventHandler { static void doEvent(EventHandler handler) { try { handler.eventBody(); } catch (RuntimeException e) { (new UnexpectedErrorDialog?()).show(); } } public abstract void eventBody(); }

Participants

Structure

Collaborations

Resulting Context

Consequences

Known Uses

Example

Implementation

Sample Code

Related Patterns


From the problem statement: "Java's GUI events are sent to directly to EventListeners? that are scattered throughout your code. There's no way to install generic code that is called before and after every EventListener?, but you want a generic exception handler or other code to wrap every event."

Actually, GUI events are not sent directly to EventListeners?. They are first placed on a platform-independent EventQueue that dispatches them to the processEvent method of the appropriate AWT component, which dispatches each event to an event-specific processNnnnn method (e.g. processMouseEvent), which then notifies any registered event listeners. Event processing can be overridden at any point in that process.

To install generic code that is invoked before/after every event, you can install a custom EventQueue that performs some processing on the events as they are queued or dispatched.

See the documentation for java.awt.EventQueue for more details.

--NatPryce


CategoryUserInterface


EditText of this page (last edited March 27, 2005) or FindPage with title or text search